package restriction

import (
	"context"
	"kami/internal/dao"
	"kami/internal/model"
	"kami/internal/model/do"
	"kami/internal/model/entity"
	"kami/utility/config"
	"kami/utility/integration/restriction"
	"net"

	"github.com/duke-git/lancet/v2/netutil"
	"github.com/duke-git/lancet/v2/pointer"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/text/gstr"
)

// GetOrSetIPRecord 获取或设置IP记录
func (i *sRestriction) GetOrSetIPRecord(ctx context.Context, ip string, tx gdb.TX) (m *model.RestrictionIPRecordOutput, err error) {
	ip = gstr.TrimAll(ip)
	db := dao.V1RestrictIpRecord.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		db = db.TX(tx)
	}
	err = db.Where(dao.V1RestrictIpRecord.Columns().Ip, ip).Scan(&m)
	if !pointer.IsNil(m) && m.Id > 0 {
		return
	}
	locationResp := restriction.Response{}
	if netutil.IsPublicIP(net.ParseIP(ip)) {
		locationResp, err = restriction.GetLocationByIP(ctx, ip)
		if err != nil {
			glog.Error(ctx, "获取IP地址失败", err)
		}
	}
	id, _ := db.InsertAndGetId(do.V1RestrictIpRecord{
		Ip:         ip,
		IpProvince: locationResp.Province,
		IsPublic:   netutil.IsPublicIP(net.ParseIP(ip)),
		RawData:    locationResp,
	})
	m = &model.RestrictionIPRecordOutput{
		V1RestrictIpRecord: entity.V1RestrictIpRecord{
			Id:         uint(id),
			Ip:         ip,
			IpProvince: locationResp.Province,
			IsPublic:   netutil.IsPublicIP(net.ParseIP(ip)),
		},
		RawData: locationResp,
	}
	return
}
