package page

import (
	"context"

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

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

// GetSearchIndexStatusUseCase retrieves search index status information
type GetSearchIndexStatusUseCase struct {
	searchClient *search.Client
	logger       *zap.Logger
}

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

// SearchIndexStatus contains search index status information
type SearchIndexStatus struct {
	Status        string // "not_created", "active", "error"
	DocumentCount int64
}

// Execute retrieves search index status for a site
func (uc *GetSearchIndexStatusUseCase) Execute(
	ctx context.Context,
	siteID gocql.UUID,
) (*SearchIndexStatus, error) {
	status := &SearchIndexStatus{
		Status:        "not_created",
		DocumentCount: 0,
	}

	// Check if index exists
	indexExists, err := uc.searchClient.IndexExists(siteID.String())
	if err != nil {
		uc.logger.Error("failed to check index existence", zap.Error(err))
		status.Status = "error"
		return status, nil
	}

	if !indexExists {
		return status, nil
	}

	// Index exists, mark as active
	status.Status = "active"

	// Get index stats
	stats, err := uc.searchClient.GetStats(siteID.String())
	if err != nil {
		uc.logger.Error("failed to get index stats", zap.Error(err))
		// Don't change status to error, index is still active
	} else {
		status.DocumentCount = stats.NumberOfDocuments
	}

	uc.logger.Info("search index status retrieved",
		zap.String("site_id", siteID.String()),
		zap.String("status", status.Status),
		zap.Int64("doc_count", status.DocumentCount))

	return status, nil
}
