// Copyright (c) 2025 a2dom - subbdom.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// File: main.go

package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"log"
	"os"

	"github.com/a2dom/subbdom-cli/utils"
	"github.com/spf13/viper"
)

var (
	version string
)

func main() {
	home, _ := os.UserHomeDir()
	viper.SetConfigName(".subbdom-cli")
	viper.SetConfigType("yaml")
	viper.AddConfigPath("/etc/subbdom-cli/")
	viper.AddConfigPath(home)

	var outputFormat string
	var dataSources string
	var zone string
	var timeout int
	flag.StringVar(&outputFormat, "o", "text", "Output format (text,json)")
	flag.StringVar(&dataSources, "ds", "db", "Datasources")
	flag.StringVar(&zone, "z", "", "Zone")
	flag.IntVar(&timeout, "t", 5, "Timeout")
	flag.Parse()

	if zone == "" {
		fmt.Println("Error: -z (zone) flag is required")
		flag.Usage()
		os.Exit(1)
	}

	if err := viper.ReadInConfig(); err != nil {
		log.Fatalf("Error reading config file: %v", err)
	}

	// Retrieve API keys from the config
	apiKey := viper.GetString("subbdom_api_key")
	if apiKey == "" {
		log.Fatal("No API keys found.")
	}

	subdomains, err := utils.FetchSubdomains(apiKey, dataSources, timeout, version, zone)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	if outputFormat == "json" {
		jsonOutput, err := json.Marshal(subdomains)
		if err != nil {
			fmt.Println("Error encoding JSON:", err)
			return
		}
		fmt.Println(string(jsonOutput))
	} else {
		for _, hostname := range subdomains {
			fmt.Println(hostname)
		}
	}
}
