package sysUser

import (
	"context"

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

	"kami/api/sysUser/v1"

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

func (c *ControllerV1) TotpImageGet(ctx context.Context, req *v1.TotpImageGetReq) (res *v1.TotpImageGetRes, err error) {
	userInfo, err := service.SysAuth().LoginOnlyLogin(ctx)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeNotAuthorized, err, "权限不足")
		return
	}
	if !mfa.ValidCode(req.Code, userInfo.OtpSecret) {
		return nil, errHandler.WrapError(ctx, errHandler.ErrLoginUserTotpError, err, "验证码错误")
	}
	otp, err := mfa.GetOtp(userInfo.Id, userInfo.Username, userInfo.OtpKey, userInfo.OtpSecret)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeInternalError, err, "获取otp失败")
		return
	}
	res = &v1.TotpImageGetRes{
		Image: otp.QrImage,
	}
	return
}
