package User

import (
	"context"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/suyuan32/simple-admin-core/rpc/types/core"
	"github.com/zeromicro/go-zero/core/errorx"
	"wechat-api/ent"
	"wechat-api/ent/creditbalance"
	"wechat-api/internal/utils"
	jwtutils "wechat-api/internal/utils/jwt"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetGptsUserBalanceLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetGptsUserBalanceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetGptsUserBalanceLogic {
	return &GetGptsUserBalanceLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx}
}

func (l *GetGptsUserBalanceLogic) GetGptsUserBalance(tokenStr string) (*types.UserBalanceResp, error) {
	resp := types.UserBalanceResp{}
	resp.Data.Balance = tea.Float32(0.0)

	claims, err := jwtutils.ParseJwtToken(l.svcCtx.Config.Auth.AccessSecret, tokenStr)
	if err != nil {
		return nil, errorx.NewInvalidArgumentError("用户未登录")
	}

	userId, ok := claims["userId"].(string)

	if !ok || userId == "" {
		return nil, errorx.NewInvalidArgumentError("用户需要登录")
	}

	userInfo, _ := l.svcCtx.CoreRpc.GetUserById(l.ctx, &core.UUIDReq{Id: userId})
	valid := utils.CheckGptLogin(userInfo.RoleIds)
	if !valid {
		return nil, errorx.NewInvalidArgumentError("用户不允许登陆")
	}

	balance, err := l.svcCtx.DB.CreditBalance.Query().Where(creditbalance.UserID(userId)).First(l.ctx)
	if err != nil && !ent.IsNotFound(err) {
		l.Logger.Errorf("get credit_balance failed:%v\n", err)
		return &resp, nil
	}
	if balance != nil {
		resp.Data.Balance = &balance.Balance
	}

	return &resp, nil
}
