package User

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"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 UpdateGptsUserPwdLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *UpdateGptsUserPwdLogic) UpdateGptsUserPwd(tokenStr string, req *types.PasswordReq) (*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("用户不允许登陆")
	}

	if req.Password2 == nil || req.Password == nil {
		return nil, errorx.NewInvalidArgumentError("参数不能为空")
	}
	password := *req.Password
	password2 := *req.Password2

	if password == "" || password2 == "" || password != password2 {
		return nil, errorx.NewInvalidArgumentError("2次密码需相同，不能为空")
	}

	_, err = l.svcCtx.CoreRpc.UpdateUser(l.ctx, &core.UserInfo{
		Id:       &userId,
		Password: &password,
	})
	if err != nil {
		return nil, err
	}

	return &types.BaseDataInfo{Msg: errormsg.Success}, nil
}
