package card_info_c_trip

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/gtime"
	"github.com/gogf/gf/v2/text/gstr"

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

	"kami/api/card_info_c_trip/v1"
)

func (c *ControllerV1) AccountCreate(ctx context.Context, req *v1.AccountCreateReq) (res *v1.AccountCreateRes, err error) {
	userInfo, err := service.SysAuth().LoginOnlyLogin(ctx)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeNotAuthorized, err, "权限不足")
		return
	}
	req.Cookie = strings.TrimSpace(req.Cookie)
	client, err2 := redeem.GetClient(consts.CardRedeemAccountCategoryCTrip)
	if err2 != nil {
		err = errHandler.WrapError(ctx, gcode.CodeInternalError, err2, "获取客户端失败")
		return
	}
	cookieUserInfo, err2 := client.QueryUserInfoWithCache(ctx, gstr.Trim(req.Cookie), gtime.M*10)
	if err2 != nil || !cookieUserInfo.Ok {
		err = errHandler.WrapError(ctx, gcode.CodeInternalError, err2, "cookie失效")
		return
	}
	existInfo, err2 := service.CardRedeemAccount().GetNormalOneByCk(ctx, consts.CardRedeemAccountCategoryCTrip, req.Cookie)
	if !pointer.IsNil(existInfo) && existInfo.Id != "" {
		err = gerror.NewCode(gcode.CodeValidationFailed, "账号已存在")
		return
	}
	balanceInfo, err2 := client.QueryBalanceWithCache(ctx, &redeemModel.QueryBalanceReq{
		Cookie: gstr.Trim(req.Cookie),
	}, gtime.M*10)
	if err2 != nil || pointer.IsNil(balanceInfo) {
		err = gerror.NewCode(gcode.CodeValidationFailed, "查询余额失败")
		return
	}
	if err = service.CardRedeemAccount().Add(ctx, &model.RedeemAccountAddInput{
		Cookie:         gstr.Trim(req.Cookie),
		Name:           req.Name,
		MaxAmountLimit: req.MaxAmountLimit,
		MaxCountLimit:  req.MaxCountLimit,
		Username:       cookieUserInfo.Username,
		Nickname:       cookieUserInfo.NickName,
		Balance:        balanceInfo.Money,
		UserId:         userInfo.Id,
		Category:       consts.CardRedeemAccountCategoryCTrip,
	}, nil); err == nil {
		_ = service.CardRedeemOrder().TriggerValidateAndConsume()
	}
	return
}
