package auth

import (
	"context"

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

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

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

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

func (l *RegisterResendLogic) RegisterResend(req *types.RegisterResendReq) (*types.RegisterData, error) {
	if err := requireRegistrationDeps(l.svcCtx); err != nil {
		return nil, err
	}

	tenant, err := resolveTenant(l.ctx, l.svcCtx, req.TenantSlug)
	if err != nil {
		return nil, err
	}

	ch, err := l.svcCtx.MemberOTP.MatchChallenge(l.ctx, &dommember.MatchChallengeRequest{
		ChallengeID:   req.ChallengeID,
		TenantID:      tenant.TenantID,
		Purpose:       registrationPurpose(),
		RequireUID:    true,
		RequireTarget: true,
	})
	if err != nil {
		return nil, err
	}

	if err := l.svcCtx.MemberOTP.Invalidate(l.ctx, req.ChallengeID); err != nil {
		return nil, err
	}

	data, err := sendRegistrationOTP(l.ctx, l.svcCtx, tenant.TenantID, ch.UID, ch.Target)
	if err != nil {
		return nil, err
	}
	data.UID = ch.UID
	return data, nil
}
