package page

import (
	"context"
	"fmt"

	"github.com/gocql/gocql"
	"go.uber.org/zap"

	"codeberg.org/mapleopentech/monorepo/cloud/maplepress-backend/pkg/search"
)

// EnsureSearchIndexUseCase ensures search index exists for a site
type EnsureSearchIndexUseCase struct {
	searchClient *search.Client
	logger       *zap.Logger
}

// ProvideEnsureSearchIndexUseCase creates a new EnsureSearchIndexUseCase
func ProvideEnsureSearchIndexUseCase(
	searchClient *search.Client,
	logger *zap.Logger,
) *EnsureSearchIndexUseCase {
	return &EnsureSearchIndexUseCase{
		searchClient: searchClient,
		logger:       logger,
	}
}

// Execute ensures the search index exists, creating it if necessary
func (uc *EnsureSearchIndexUseCase) Execute(ctx context.Context, siteID gocql.UUID) error {
	indexExists, err := uc.searchClient.IndexExists(siteID.String())
	if err != nil {
		uc.logger.Error("failed to check index existence", zap.Error(err))
		return fmt.Errorf("failed to check search index: %w", err)
	}

	if !indexExists {
		uc.logger.Info("creating search index", zap.String("site_id", siteID.String()))
		if err := uc.searchClient.CreateIndex(siteID.String()); err != nil {
			uc.logger.Error("failed to create index", zap.Error(err))
			return fmt.Errorf("failed to create search index: %w", err)
		}
	}

	return nil
}
