package auth

import (
	"context"
	"strings"

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

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

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

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

func (l *RegisterConfirmLogic) RegisterConfirm(req *types.RegisterConfirmReq) (*types.AuthTokenData, error) {
	if l.svcCtx.MemberOTP == nil || l.svcCtx.MemberLifecycle == nil {
		return nil, errb.SysNotImplemented("member module not configured")
	}
	if l.svcCtx.AuthToken == nil {
		return nil, errb.SysNotImplemented("auth token not configured")
	}

	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: false,
	})
	if err != nil {
		return nil, err
	}

	if _, err := l.svcCtx.MemberOTP.Verify(l.ctx, &dommember.VerifyOTPRequest{
		TenantID:    tenant.TenantID,
		UID:         ch.UID,
		ChallengeID: req.ChallengeID,
		Code:        req.Code,
		Purpose:     registrationPurpose(),
	}); err != nil {
		return nil, err
	}

	if err := l.svcCtx.MemberLifecycle.Activate(l.ctx, tenant.TenantID, ch.UID); err != nil {
		return nil, err
	}

	// Email 註冊 OTP 已證明使用者擁有該信箱；同步為已驗證的商業聯絡 Email，
	// 避免完成註冊後仍要在安全設定重驗同一個地址。
	if email := strings.TrimSpace(strings.ToLower(ch.Target)); email != "" && l.svcCtx.MemberProfile != nil {
		if err := l.svcCtx.MemberProfile.SetBusinessEmailVerified(l.ctx, tenant.TenantID, ch.UID, email); err != nil {
			return nil, err
		}
	}

	return issueAuthToken(l.ctx, l.svcCtx, tenant.TenantID, ch.UID)
}
