// codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/usecase/blockedemail/delete.go
package blockedemail

import (
	"context"
	"strings"

	"go.uber.org/zap"

	"github.com/gocql/gocql"
	dom_blockedemail "codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/domain/blockedemail"
	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/pkg/httperror"
	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/pkg/validation"
)

type DeleteBlockedEmailUseCase interface {
	Execute(ctx context.Context, userID gocql.UUID, email string) error
}

type deleteBlockedEmailUseCaseImpl struct {
	logger *zap.Logger
	repo   dom_blockedemail.BlockedEmailRepository
}

func NewDeleteBlockedEmailUseCase(
	logger *zap.Logger,
	repo dom_blockedemail.BlockedEmailRepository,
) DeleteBlockedEmailUseCase {
	logger = logger.Named("DeleteBlockedEmailUseCase")
	return &deleteBlockedEmailUseCaseImpl{
		logger: logger,
		repo:   repo,
	}
}

func (uc *deleteBlockedEmailUseCaseImpl) Execute(ctx context.Context, userID gocql.UUID, email string) error {
	// Normalize email
	normalizedEmail := strings.ToLower(strings.TrimSpace(email))

	// Check if email exists in blocked list
	existing, err := uc.repo.Get(ctx, userID, normalizedEmail)
	if err != nil {
		uc.logger.Error("Failed to check existing blocked email",
			zap.Any("error", err),
			zap.Any("user_id", userID),
			zap.String("email", validation.MaskEmail(normalizedEmail)))
		return err
	}

	if existing == nil {
		uc.logger.Debug("Blocked email not found",
			zap.Any("user_id", userID),
			zap.String("email", validation.MaskEmail(normalizedEmail)))
		return httperror.NewNotFoundError("Email not found in blocked list")
	}

	// Delete blocked email
	err = uc.repo.Delete(ctx, userID, normalizedEmail)
	if err != nil {
		uc.logger.Error("Failed to delete blocked email",
			zap.Any("error", err),
			zap.Any("user_id", userID),
			zap.String("email", validation.MaskEmail(normalizedEmail)))
		return err
	}

	uc.logger.Info("Blocked email deleted",
		zap.Any("user_id", userID),
		zap.String("email", validation.MaskEmail(normalizedEmail)))

	return nil
}
