package app

import (
	"fmt"
	"log/slog"
	"net"
	g "proxy-server/gateway/globals"
	"strings"
)

func IpGeo(ip net.IP) (info *IpGeoInfo, err error) {
	defer func() {
		var rs = recover()
		if reErr, ok := rs.(error); ok {
			err = fmt.Errorf("执行归属地查询异常 %w", reErr)
		}
	}()

	// 本地归属地查询
	str, err := g.Geo.SearchByStr(ip.String())
	if err != nil {
		return nil, err
	}

	if str != "" {
		slog.Debug("本地解析归属地结果", "str", str)
		values := strings.Split(str, "|")
		if len(values) != 5 {
			return nil, fmt.Errorf("本地归属地查询解析失败")
		}

		var info = &IpGeoInfo{}

		if values[2] != "0" {
			info.Prov = values[2]
		}
		if values[3] != "0" {
			info.City = values[3]
		}
		if values[4] != "0" {
			info.Isp = values[4]
		}
		return info, nil
	}

	return nil, fmt.Errorf("本地归属地查询为空")
}

type IpGeoInfo struct {
	Prov string
	City string
	Isp  string
}
