package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

// NameSilo API 响应结构
type NameSiloAPIResponse struct {
	Request struct {
		Operation string `json:"operation"`
		IP        string `json:"ip"`
	} `json:"request"`
	Reply struct {
		Code            int    `json:"code"`
		Detail          string `json:"detail"`
		ResourceRecords []struct {
			RecordID string          `json:"record_id"`
			Type     string          `json:"type"`
			Host     string          `json:"host"`
			Value    string          `json:"value"`
			TTL      string          `json:"ttl"`
			Distance json.RawMessage `json:"distance"` // 兼容数字和字符串
		} `json:"resource_record"`
	} `json:"reply"`
}

// 解析 distance，兼容数字和字符串
func parseDistance(raw json.RawMessage) string {
	var str string
	if err := json.Unmarshal(raw, &str); err == nil {
		return str
	}
	var num int
	if err := json.Unmarshal(raw, &num); err == nil {
		return fmt.Sprintf("%d", num)
	}
	return "0"
}

// RetrieveDNSRecords 使用 Namesilo API 获取指定域名的所有 DNS 记录
func RetrieveDNSRecords(apiKey, domain string) (*NameSiloAPIResponse, error) {
	url := fmt.Sprintf("https://www.namesilo.com/api/dnsListRecords?version=1&type=json&key=%s&domain=%s", apiKey, domain)

	resp, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	var apiResponse NameSiloAPIResponse
	if err := json.Unmarshal(body, &apiResponse); err != nil {
		return nil, err
	}

	return &apiResponse, nil
}

// FetchSubdomainRecord 获取指定子域名的 DNS 记录信息
func FetchSubdomainRecord(key string, domain string, Subdomain string) string {

	// 获取 DNS 记录
	response, err := RetrieveDNSRecords(key, domain)
	if err != nil {
		fmt.Println("获取 DNS 记录失败:", err)
		return "NULL"
	}

	// 打印完整 JSON 数据
	_, err = json.MarshalIndent(response, "", "  ")
	if err != nil {
		fmt.Println("JSON 格式化失败:", err)
		return "NULL"
	}

	// 只获取指定子域名的信息
	for _, record := range response.Reply.ResourceRecords {
		if record.Host == Subdomain {
			fmt.Printf("RecordID: %s, Host: %s, Type: %s, Value: %s, TTL: %s, Distance: %s\n",
				record.RecordID, record.Host, record.Type, record.Value, record.TTL, parseDistance(record.Distance))

			return record.RecordID
		}
	}

	return "NULL"
}
