package tenant

import (
	"context"

	"go.uber.org/zap"

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

// ValidateTenantSlugUniqueUseCase validates that a tenant slug is unique
type ValidateTenantSlugUniqueUseCase struct {
	repo   domaintenant.Repository
	logger *zap.Logger
}

// ProvideValidateTenantSlugUniqueUseCase creates a new ValidateTenantSlugUniqueUseCase
func ProvideValidateTenantSlugUniqueUseCase(
	repo domaintenant.Repository,
	logger *zap.Logger,
) *ValidateTenantSlugUniqueUseCase {
	return &ValidateTenantSlugUniqueUseCase{
		repo:   repo,
		logger: logger.Named("validate-tenant-slug-unique-usecase"),
	}
}

// Execute validates that a tenant slug is unique (not already taken)
func (uc *ValidateTenantSlugUniqueUseCase) Execute(ctx context.Context, slug string) error {
	existing, err := uc.repo.GetBySlug(ctx, slug)
	if err == nil && existing != nil {
		// CWE-532: Use redacted tenant slug for logging
		uc.logger.Warn("tenant slug already exists",
			logger.TenantSlugHash(slug),
			logger.SafeTenantSlug("tenant_slug_redacted", slug))
		return domaintenant.ErrTenantExists
	}

	// Ignore "not found" error (expected case - slug is available)
	if err != nil && err != domaintenant.ErrTenantNotFound {
		uc.logger.Error("failed to check tenant slug uniqueness", zap.Error(err))
		return err
	}

	// CWE-532: Use redacted tenant slug for logging
	uc.logger.Debug("tenant slug is unique",
		logger.TenantSlugHash(slug),
		logger.SafeTenantSlug("tenant_slug_redacted", slug))
	return nil
}
