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

import (
	"context"
	"strings"
	"time"

	"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"
)

const MaxBlockedEmails = 100

type CreateBlockedEmailUseCase interface {
	Execute(ctx context.Context, userID gocql.UUID, email string, blockedUserID gocql.UUID, reason string) (*dom_blockedemail.BlockedEmail, error)
}

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

func NewCreateBlockedEmailUseCase(
	logger *zap.Logger,
	repo dom_blockedemail.BlockedEmailRepository,
) CreateBlockedEmailUseCase {
	logger = logger.Named("CreateBlockedEmailUseCase")
	return &createBlockedEmailUseCaseImpl{
		logger: logger,
		repo:   repo,
	}
}

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

	// Check if email is already blocked
	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 nil, err
	}

	if existing != nil {
		uc.logger.Debug("Email already blocked",
			zap.Any("user_id", userID),
			zap.String("email", validation.MaskEmail(normalizedEmail)))
		return nil, httperror.NewConflictError("This email is already blocked")
	}

	// Check limit
	count, err := uc.repo.Count(ctx, userID)
	if err != nil {
		uc.logger.Error("Failed to count blocked emails",
			zap.Any("error", err),
			zap.Any("user_id", userID))
		return nil, err
	}

	if count >= MaxBlockedEmails {
		uc.logger.Warn("Blocked email limit reached",
			zap.Any("user_id", userID),
			zap.Int("count", count),
			zap.Int("limit", MaxBlockedEmails))
		return nil, httperror.NewBadRequestError("You have reached the maximum number of blocked emails")
	}

	// Create blocked email entry
	blockedEmail := &dom_blockedemail.BlockedEmail{
		UserID:        userID,
		BlockedEmail:  normalizedEmail,
		BlockedUserID: blockedUserID,
		Reason:        reason,
		CreatedAt:     time.Now().UTC(),
	}

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

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

	return blockedEmail, nil
}
