package sysUser

import (
	"context"

	"kami/internal/dao"
	"kami/internal/model/do"
	"kami/internal/model/entity"
	"kami/utility/config"
	"kami/utility/mfa"
	"kami/utility/utils"

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

// SetTotp 设置totp
func (s *sSysUser) SetTotp(ctx context.Context, data *entity.V1SysUser, key, secret string) (err error) {
	if data == nil {
		err = gerror.New("用户不存在")
		return
	}
	otp, err := mfa.GetOtp(data.Id, data.Username, key, secret)
	if err != nil {
		return
	}
	_, err = dao.V1SysUser.Ctx(ctx).DB(config.GetDatabaseV1()).
		Where(dao.V1SysUser.Columns().Id, data.Id).
		Update(do.V1SysUser{
			OtpKey:    otp.Key,
			OtpSecret: otp.Secret,
		})
	err = utils.HandleNoRowsError(err)
	return
}

// ResetTotp 重置两步验证
func (s *sSysUser) ResetTotp(ctx context.Context, data *entity.V1SysUser) (err error) {
	if data == nil {
		err = gerror.New("用户不存在")
		return
	}
	_, err = dao.V1SysUser.Ctx(ctx).DB(config.GetDatabaseV1()).
		Where(dao.V1SysUser.Columns().Id, data.Id).
		Update(do.V1SysUser{
			OtpKey:    "",
			OtpSecret: "",
		})
	return
}
