package User

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

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

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

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

func (l *GetGptsUserInfoLogic) GetGptsUserInfo(tokenStr string) (*types.UserInfoResp, error) {
	resp := types.UserInfoResp{}

	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("用户不允许登陆")
	}

	resp.Data.Username = userInfo.Username
	resp.Data.Nickname = userInfo.Nickname
	resp.Data.Id = &userId
	resp.Data.Status = userInfo.Status
	resp.Data.Mobile = userInfo.Mobile
	resp.Data.Email = userInfo.Email
	return &resp, nil
}
