package page

import (
	"context"
	"fmt"

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

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

// ExecuteSearchQueryUseCase performs the actual search query
type ExecuteSearchQueryUseCase struct {
	searchClient *search.Client
	logger       *zap.Logger
}

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

// Execute performs the search query against Meilisearch
func (uc *ExecuteSearchQueryUseCase) Execute(
	ctx context.Context,
	siteID gocql.UUID,
	query string,
	limit, offset int64,
	filter string,
) (*search.SearchResult, error) {
	// Set default limits if not provided
	if limit <= 0 || limit > 100 {
		limit = 20 // Default to 20 results
	}

	if offset < 0 {
		offset = 0
	}

	// Build search request
	searchReq := search.SearchRequest{
		Query:  query,
		Limit:  limit,
		Offset: offset,
		Filter: filter,
	}

	// If no filter provided, default to only published pages
	if searchReq.Filter == "" {
		searchReq.Filter = "status = publish"
	}

	// Perform search
	result, err := uc.searchClient.Search(siteID.String(), searchReq)
	if err != nil {
		uc.logger.Error("failed to search pages", zap.Error(err))
		return nil, fmt.Errorf("failed to search pages: %w", err)
	}

	uc.logger.Info("search completed",
		zap.String("site_id", siteID.String()),
		zap.String("query", query),
		zap.Int64("total_hits", result.TotalHits),
		zap.Int64("processing_time_ms", result.ProcessingTimeMs))

	return result, nil
}
