package tenant

import (
	"context"
	"fmt"

	"go.uber.org/zap"

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

// SaveTenantToRepoUseCase saves a tenant to the repository
type SaveTenantToRepoUseCase struct {
	repo   domaintenant.Repository
	logger *zap.Logger
}

// ProvideSaveTenantToRepoUseCase creates a new SaveTenantToRepoUseCase
func ProvideSaveTenantToRepoUseCase(
	repo domaintenant.Repository,
	logger *zap.Logger,
) *SaveTenantToRepoUseCase {
	return &SaveTenantToRepoUseCase{
		repo:   repo,
		logger: logger.Named("save-tenant-to-repo-usecase"),
	}
}

// Execute saves a tenant to the repository
func (uc *SaveTenantToRepoUseCase) Execute(ctx context.Context, tenant *domaintenant.Tenant) error {
	if err := uc.repo.Create(ctx, tenant); err != nil {
		uc.logger.Error("failed to create tenant in repository",
			zap.String("tenant_id", tenant.ID),
			zap.String("slug", tenant.Slug),
			zap.Error(err))
		return fmt.Errorf("failed to create tenant: %w", err)
	}

	uc.logger.Info("tenant saved to repository",
		zap.String("tenant_id", tenant.ID),
		zap.String("slug", tenant.Slug))

	return nil
}
