package external

import (
	"fmt"
	"go-account-register/models"
	"go-account-register/utils"
	"time"
)

func GetIpInfo(ip string) models.Ip {
	db := utils.GetDB()
	var ipInfo models.Ip
	if ip == "" {
		var ipRequest utils.IpRequest
		res, err := ipRequest.IpApi(ip)
		if err != nil {
		}
		resIp := db.Model(&models.Ip{}).Where("query = ?", res.Query).First(&ipInfo)
		if resIp.Error != nil {
			createIp(res)
			db.Model(&models.Ip{}).Where("query = ?", res.Query).First(&ipInfo)
			return ipInfo
		}
		return ipInfo
	}
	resIp := db.Model(&models.Ip{}).Where("query = ?", ip).First(&ipInfo)
	if resIp.Error != nil {
		var ipRequest utils.IpRequest
		res, err := ipRequest.IpApi(ip)
		if err != nil {
		}
		createIp(res)
		db.Model(&models.Ip{}).Where("query = ?", ip).First(&ipInfo)
		return ipInfo
	}

	return ipInfo
}

func createIp(res utils.IPAPIResponse) {
	db := utils.GetDB()

	db.Model(&models.Ip{}).Create(&models.Ip{
		As:            res.As,
		Asname:        res.Asname,
		City:          res.City,
		Continent:     res.Continent,
		ContinentCode: res.ContinentCode,
		Country:       res.Country,
		CountryCode:   res.CountryCode,
		Currency:      res.Currency,
		District:      res.District,
		Hosting:       utils.BoolToInt(res.Hosting),
		Isp:           res.Isp,
		Lat:           fmt.Sprint(res.Lat),
		Lon:           fmt.Sprint(res.Lon),
		Mobile:        utils.BoolToInt(res.Mobile),
		Offset:        fmt.Sprint(res.Offset),
		Org:           res.Org,
		Proxy:         utils.BoolToInt(res.Proxy),
		Query:         res.Query,
		Region:        res.Region,
		RegionName:    res.RegionName,
		Timezone:      res.Timezone,
		Zip:           res.Zip,
		UpdateTime:    time.Now().Unix(),
		CreateTime:    time.Now().Unix(),
	})
}
