package user

import (
	"context"

	"go.uber.org/zap"

	domainuser "codeberg.org/mapleopentech/monorepo/cloud/maplepress-backend/internal/domain/user"
	"codeberg.org/mapleopentech/monorepo/cloud/maplepress-backend/pkg/logger"
)

// ValidateUserEmailUniqueUseCase validates that a user email is unique within a tenant
type ValidateUserEmailUniqueUseCase struct {
	repo   domainuser.Repository
	logger *zap.Logger
}

// ProvideValidateUserEmailUniqueUseCase creates a new ValidateUserEmailUniqueUseCase
func ProvideValidateUserEmailUniqueUseCase(
	repo domainuser.Repository,
	logger *zap.Logger,
) *ValidateUserEmailUniqueUseCase {
	return &ValidateUserEmailUniqueUseCase{
		repo:   repo,
		logger: logger.Named("validate-user-email-unique-usecase"),
	}
}

// Execute validates that a user email is unique within a tenant
func (uc *ValidateUserEmailUniqueUseCase) Execute(ctx context.Context, tenantID, email string) error {
	existing, err := uc.repo.GetByEmail(ctx, tenantID, email)
	if err == nil && existing != nil {
		// CWE-532: Use redacted email for logging
		uc.logger.Warn("user email already exists",
			logger.EmailHash(email),
			logger.SafeEmail("email_redacted", email),
			zap.String("tenant_id", tenantID))
		return domainuser.ErrUserAlreadyExists
	}

	// Ignore ErrUserNotFound - it's expected (email is available)
	if err != nil && err != domainuser.ErrUserNotFound {
		uc.logger.Error("failed to check user email uniqueness", zap.Error(err))
		return err
	}

	// CWE-532: Use redacted email for logging
	uc.logger.Debug("user email is unique",
		logger.EmailHash(email),
		logger.SafeEmail("email_redacted", email),
		zap.String("tenant_id", tenantID))
	return nil
}
