package card_info_jd

import (
	"context"
	"kami/internal/consts"
	"kami/internal/errHandler"
	"kami/internal/model"
	"kami/internal/service"
	redeemModel "kami/utility/integration/redeem"
	redeem "kami/utility/integration/redeem/client"

	"github.com/duke-git/lancet/v2/pointer"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/os/glog"

	"strings"

	"kami/api/card_info_jd/v1"
)

func (c *ControllerV1) JDAccountCookieCheck(ctx context.Context, req *v1.JDAccountCookieCheckReq) (res *v1.JDAccountCookieCheckRes, err error) {
	userInfo, err := service.SysAuth().LoginWithIFrameAndLogin(ctx)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeNotAuthorized, err, "权限不足")
		return
	}

	//限流
	if !pointer.IsNil(userInfo) && userInfo.Id != "" {
		//接口限流，同一个用户2秒内只能访问1次
		if !service.Rate().Allow(ctx, model.LimiterTypeCardInfoJdAccountCookieChecker, userInfo.Id) {
			return nil, gerror.NewCode(gcode.CodeSecurityReason, "操作过于频繁，请稍后再试")
		}
	}

	res = &v1.JDAccountCookieCheckRes{
		IsAvailable: false,
	}

	client, err2 := redeem.GetClient(consts.CardRedeemAccountCategoryJD)
	if err2 != nil {
		glog.Error(ctx, "获取客户端失败", err2)
		return
	}

	jdUserInfo, err2 := client.QueryUserInfo(ctx, strings.TrimSpace(req.Cookie))
	if err2 != nil || pointer.IsNil(jdUserInfo) || !jdUserInfo.Ok {
		return
	}
	res.IsAvailable = true
	res.Nickname = jdUserInfo.NickName
	res.Username = jdUserInfo.Username
	result, err2 := client.QueryBalance(ctx, &redeemModel.QueryBalanceReq{
		Cookie: strings.TrimSpace(req.Cookie),
	})
	if err2 != nil {
		return
	}
	res.Balance = result.Money
	existJdUserInfo, _ := service.CardRedeemAccount().GetNormalOneByUsername(ctx, jdUserInfo.Username, consts.CardRedeemAccountCategoryJD)
	if !pointer.IsNil(existJdUserInfo) && existJdUserInfo.Id != "" {
		res.IsExist = true
	}
	return
}
