package sysUser

import (
	"context"

	"kami/utility/mfa"

	v1 "kami/api/sysUser/v1"
	"kami/internal/errHandler"
	"kami/internal/model"
	"kami/internal/service"
	"kami/utility/utils"

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

func (c *ControllerV1) UserChangePwd(ctx context.Context, req *v1.UserChangePwdReq) (res *v1.UserChangePwdRes, err error) {
	userService := service.SysUser()
	userItem, err := service.SysAuth().LoginWithIFrameAndLogin(ctx)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeNotAuthorized, err, "权限不足")
		return
	}
	if userItem.UserPassword != utils.EncryptPassword(req.OldPassword, userItem.UserSalt) {
		err = gerror.NewCode(gcode.CodeNotAuthorized, "旧密码错误")
		return
	}
	if userItem.OtpSecret != "" && !mfa.ValidCode(req.TotpCode, userItem.OtpSecret) {
		err = gerror.NewCode(gcode.CodeValidationFailed, "二次验证错误")
		return
	}
	err = userService.ChangePwd(ctx, &model.UserChangePwdInput{
		UserChangePwdReq: *req,
		UserId:           userItem.Id,
	})
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeInternalError, err, "修改密码失败")
	}
	return
}
