package card_info_original_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"
	"strings"

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

	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"

	"kami/api/card_info_original_jd/v1"
)

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

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

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

	client, err2 := redeem.GetClient(consts.CardRedeemAccountCategoryOriginalJD)
	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.CardRedeemAccountCategoryOriginalJD)
	if !pointer.IsNil(existJdUserInfo) && existJdUserInfo.Id != "" {
		res.IsExist = true
	}
	return
}
