package page

import (
	"context"

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

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

// DeletePagesFromSearchUseCase deletes pages from the search index
type DeletePagesFromSearchUseCase struct {
	searchClient *search.Client
	logger       *zap.Logger
}

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

// Execute deletes specific pages from the search index
func (uc *DeletePagesFromSearchUseCase) Execute(
	ctx context.Context,
	siteID gocql.UUID,
	pageIDs []string,
) (int, error) {
	if len(pageIDs) == 0 {
		return 0, nil
	}

	deindexedCount := 0

	// Batch delete from Meilisearch
	if len(pageIDs) > 1 {
		_, err := uc.searchClient.DeleteDocuments(siteID.String(), pageIDs)
		if err != nil {
			uc.logger.Error("failed to delete documents from search index", zap.Error(err))
			// Don't fail the whole operation since database delete may have succeeded
			return 0, nil
		}
		deindexedCount = len(pageIDs)
	} else {
		// Single document delete
		_, err := uc.searchClient.DeleteDocument(siteID.String(), pageIDs[0])
		if err != nil {
			uc.logger.Error("failed to delete document from search index",
				zap.String("page_id", pageIDs[0]),
				zap.Error(err))
			// Don't fail the whole operation since database delete may have succeeded
			return 0, nil
		}
		deindexedCount = 1
	}

	return deindexedCount, nil
}

// ExecuteDeleteAll deletes all documents for a site from the search index
func (uc *DeletePagesFromSearchUseCase) ExecuteDeleteAll(
	ctx context.Context,
	siteID gocql.UUID,
) error {
	_, err := uc.searchClient.DeleteAllDocuments(siteID.String())
	if err != nil {
		uc.logger.Error("failed to delete all documents from search index", zap.Error(err))
		// Don't fail the whole operation since database delete may have succeeded
		return nil
	}

	return nil
}
