// Code scaffolded by goctl. Safe to edit.
package member

import (
	"context"

	domusecase "gateway/internal/model/member/domain/usecase"
	"gateway/internal/svc"
	"gateway/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type StartTOTPEnrollLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *StartTOTPEnrollLogic) StartTOTPEnroll() (*types.TOTPEnrollStartData, error) {
	actor, err := actorOrErr(l.ctx)
	if err != nil {
		return nil, err
	}
	if err := requireTOTP(l.svcCtx); err != nil {
		return nil, err
	}
	account := actor.UID
	if l.svcCtx.MemberProfile != nil {
		if me, getErr := l.svcCtx.MemberProfile.GetByUID(l.ctx, &domusecase.GetMemberRequest{
			TenantID: actor.TenantID,
			UID:      actor.UID,
		}); getErr == nil && me.BusinessEmail != "" {
			account = me.BusinessEmail
		}
	}
	start, err := l.svcCtx.MemberTOTP.StartEnroll(l.ctx, actor.TenantID, actor.UID, account)
	if err != nil {
		return nil, err
	}
	return &types.TOTPEnrollStartData{
		OtpauthURL: start.OtpauthURL,
		Issuer:     start.Issuer,
		Account:    start.Account,
		Digits:     start.Digits,
		PeriodSec:  start.PeriodSec,
		ExpiresIn:  start.ExpiresIn,
	}, nil
}
