package sysUser

import (
	"context"

	"kami/internal/errHandler"
	"kami/internal/service"
	"kami/utility/mfa"
	"kami/utility/utils"

	"kami/api/sysUser/v1"

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

func (c *ControllerV1) TotpSet(ctx context.Context, req *v1.TotpSetReq) (res *v1.TotpSetRes, err error) {
	userInfo, err := service.SysAuth().LoginOnlyLogin(ctx)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeNotAuthorized, err, "权限不足")
		return
	}
	userService := service.SysUser()
	if utils.EncryptPassword(req.Password, userInfo.UserSalt) != userInfo.UserPassword {
		err = errHandler.WrapError(ctx, errHandler.ErrLoginUserPasswordError, err)
		return
	}
	if !mfa.ValidCode(req.Code, req.OtpSecret) {
		err = errHandler.WrapError(ctx, errHandler.ErrLoginUserTotpError, err)
		return
	}
	err = userService.SetTotp(ctx, userInfo, req.OtpKey, req.OtpSecret)
	return
}
