package User

import (
	"context"
	"github.com/suyuan32/simple-admin-core/rpc/types/core"
	"github.com/zeromicro/go-zero/core/errorx"
	"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 UpdateGptsUserInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *UpdateGptsUserInfoLogic) UpdateGptsUserInfo(req *types.UserInfo, tokenStr string) (*types.BaseDataInfo, error) {
	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 := types.BaseDataInfo{}
	var mobile, nickname, email string
	if req.Email != nil && *req.Email != "" {
		email = *req.Email
	}
	if req.Mobile != nil && *req.Mobile != "" {
		mobile = *req.Mobile
	}
	if req.Nickname != nil && *req.Nickname != "" {
		nickname = *req.Nickname
	}
	_, err = l.svcCtx.CoreRpc.UpdateUser(l.ctx, &core.UserInfo{
		Id:       &userId,
		Mobile:   &mobile,
		Nickname: &nickname,
		Email:    &email,
	})
	if err != nil {
		return nil, errorx.NewInvalidArgumentError(err.Error())
	}

	return &resp, nil
}
