package card_info_walmart

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_walmart/v1"
)

func (c *ControllerV1) AccountCookieCheck(ctx context.Context, req *v1.AccountCookieCheckReq) (res *v1.AccountCookieCheckRes, 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 != "" {
		//接口限流，同一个ip一分钟内只能访问5次
		if !service.Rate().Allow(ctx, model.LimiterTypeCardInfoRedeemAccountCookieChecker, userInfo.Id) {
			return nil, gerror.NewCode(gcode.CodeSecurityReason, "操作过于频繁，请稍后再试")
		}
	}
	res = &v1.AccountCookieCheckRes{
		IsAvailable: false,
	}

	client, err2 := redeem.GetClient(consts.CardRedeemAccountCategoryWalMart)
	if err2 != nil {
		glog.Error(ctx, err2)
		return
	}

	//TODO: 沃尔玛没有用户信息
	redeemUserInfo, err2 := client.QueryUserInfo(ctx, strings.TrimSpace(req.Cookie))
	if err2 != nil || pointer.IsNil(redeemUserInfo) || !redeemUserInfo.Ok {
		return
	}

	res.IsAvailable = true
	res.Nickname = redeemUserInfo.NickName
	res.Username = redeemUserInfo.Username

	result, err2 := client.QueryBalance(ctx, &redeemModel.QueryBalanceReq{
		Cookie: strings.TrimSpace(req.Cookie),
	})
	if err2 != nil {
		err = gerror.NewCode(gcode.CodeInternalError, "查询余额失败")
		return
	}

	res.IsAvailable = result.Ok
	res.Balance = result.Money
	glog.Info(ctx, result)
	existRedeemUserInfo, _ := service.CardRedeemAccount().GetNormalOneByCk(ctx, consts.CardRedeemAccountCategoryWalMart, req.Cookie)
	if !pointer.IsNil(existRedeemUserInfo) && existRedeemUserInfo.Id != "" {
		res.IsExist = true
	}

	return
}
