package service

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

	"gitlab.com/tensorsecurity-rd/waf-console/internal/model"
)

var fakePrivateData = `{
    "data": [
        {
            "ioc": "159.203.93.255",
            "host": "10.65.135.204",
            "intelligence": [
                {
                    "judgments": [
                        "Exploit"
                    ],
                    "severity": "low",
                    "ban": {
                        "banned": 1,
                        "reason": "The IP address belongs to DigitalOcean, LLC, it is recommended to assess and handle it accordingly."
                    },
                    "basic": {
                        "carrier": "DigitalOcean, LLC",
                        "location": {
                            "country": "美国",
                            "country_code": "US",
                            "province": "新泽西州",
                            "city": "克利夫顿",
                            "lng": -74.16366,
                            "lat": 40.858402
                        }
                    },
                    "asn": {
                        "number": "14061",
                        "info": "DIGITALOCEAN-ASN - DigitalOcean, LLC, US"
                    },
                    "ioc_type": "ipv4",
                    "confidence_level": "low",
                    "is_malicious": true,
                    "source_name": "微步在线-IP信誉",
                    "update_time": 1719268503000
                }
            ]
        }
    ],
    "response_code": 0,
    "verbose_msg": "success"
}`

type ipServicePrivate struct {
	URL    string
	ApiKey string
	// ipQueryUrl      string
	ipReputationUrl string
	// ipInfoMap       map[string]IpInfo
	// useCachedIPInfo bool
	// ipInfoCache     *expirable.LRU[string, IPInfoPrivate]
}

// func NewIpServicePrivate(url, apiKey string, useCachedIPInfo bool) Service {
// 	var ipReputationUrl string
// 	reputationUrl := os.Getenv("IP_REPUTATION_URL")
// 	logging.Get().Info().Msgf("reputationUrl: %s", reputationUrl)
// 	if reputationUrl != "" {
// 		ipReputationUrl = reputationUrl
// 	} else {
// 		ipReputationUrl = fmt.Sprintf("%s?apikey=%s&resource=", ipReputation, apiKey)
// 	}
// 	logging.Get().Info().Msgf("ipReputationUrl: %s", ipReputationUrl)
// 	return &ipServicePrivate{
// 		URL:             url,
// 		ApiKey:          apiKey,
// 		ipReputationUrl: ipReputationUrl,
// 	}
// }

func (s *ipServicePrivate) QueryIP(ip string) (*model.IPInfo, error) {
	url := s.ipReputationUrl + ip
	respData, err := http.DefaultClient.Get(url)
	if err != nil {
		return nil, err
	}
	defer respData.Body.Close()

	body, err := io.ReadAll(respData.Body)
	if err != nil {
		return nil, fmt.Errorf("query ip info failed: %w", err)
	}

	var resp IPInfoPrivateResp
	if err := json.Unmarshal(body, &resp); err != nil {
		return nil, fmt.Errorf("unmarshal response failed: %w", err)
	}

	if len(resp.Data) == 0 || len(resp.Data[0].Intelligence) == 0 {
		return nil, fmt.Errorf("no data found for ip %s", ip)
	}

	info := resp.Data[0].Intelligence[0]
	tagsClasses := make([]model.TagsClass, 0, 5)
	for k, v := range info.TagsClasses {
		for _, tag := range v {
			tagsClasses = append(tagsClasses, model.TagsClass{
				TagsType: k,
				Tags:     tag,
			})
		}
	}
	return &model.IPInfo{
		Carrier: info.Basic.Carrier,
		Location: model.Location{
			Country:     info.Basic.Location.Country,
			CountryCode: info.Basic.Location.CountryCode,
			Province:    info.Basic.Location.Province,
			City:        info.Basic.Location.City,
			Longitude:   info.Basic.Location.Longitude,
			Latitude:    info.Basic.Location.Latitude,
		},
		Asn: model.ASN{
			Number: func() int { n, _ := strconv.Atoi(info.ASN.Number); return n }(),
			Info:   info.ASN.Info,
		},
		Scene:       info.Scene,
		IsMalicious: info.IsMalicious,
		Judgments:   info.Judgments,
		TagsClasses: tagsClasses,
	}, nil
}
