package restriction

import (
	"context"
	"fmt"
	"kami/api/restriction/v1"
	"kami/internal/errHandler"
	"kami/internal/model"
	"kami/internal/service"

	"github.com/gogf/gf/v2/crypto/gaes"
	"github.com/gogf/gf/v2/crypto/gmd5"
	"github.com/gogf/gf/v2/encoding/gbase64"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/net/ghttp"
)

type responseModel struct {
	IPs         []string `json:"ips"`
	DeviceID    string   `json:"deviceId"`
	DeviceModel string   `json:"deviceModel"`
	UserAgent   string   `json:"userAgent"`
}

type responseWithSign struct {
	Sign string `json:"sign"`
	responseModel
}

func (m *responseModel) GetSign() string {
	return gmd5.MustEncrypt(gjson.MustEncodeString(m))
}

func (c *ControllerV1) UserInfoCollection(ctx context.Context, req *v1.UserInfoCollectionReq) (res *v1.UserInfoCollectionRes, err error) {
	result, err := gaes.DecryptCBC(gbase64.MustDecodeString(req.Data), []byte("veuiyigemima1231"), []byte("1234567890123456"))
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeValidationFailed, err, "解密失败")
	}
	r := responseWithSign{}
	if err = gjson.DecodeTo(result, &r); err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeValidationFailed, err, "解析失败")
	}
	if r.GetSign() != r.Sign || r.Sign == "" {
		return nil, errHandler.WrapError(ctx, gcode.CodeValidationFailed, gerror.New(fmt.Sprintf("签名错误，原本签名，%s，新签名：%s", r.Sign, r.GetSign())), "签名错误")
	}
	//获取请求IP地址
	remoteIP := ghttp.RequestFromCtx(ctx).GetClientIp()
	//判断remoteIP是否与采集的IP相同，如果不相同就是代理
	_, err = service.Restriction().SaveDeviceInfo(ctx, &model.RestrictionDeviceInput{
		IPs:         r.IPs,
		RemoteIP:    remoteIP,
		DeviceID:    r.DeviceID,
		DeviceModel: r.DeviceModel,
		UserAgent:   r.UserAgent,
	})
	err = errHandler.WrapError(ctx, gcode.CodeInvalidParameter, err, "保存设备信息失败")
	return
}
