<?php

declare(strict_types=1);

namespace App\Framework\Search;

use App\Framework\Attributes\EventListener;

/**
 * Event listener for automatic search indexing without modifying entities
 */
final readonly class SearchEventListener
{
    public function __construct(
        private SearchIndexingService $indexingService
    ) {
    }

    /**
     * Handle entity creation events
     */
    #[EventListener(event: 'entity.created')]
    public function onEntityCreated(object $event): void
    {
        if (method_exists($event, 'getEntity')) {
            $entity = $event->getEntity();

            if ($this->indexingService->shouldAutoIndex($entity)) {
                $this->indexingService->indexEntity($entity);
            }
        }
    }

    /**
     * Handle entity update events
     */
    #[EventListener(event: 'entity.updated')]
    public function onEntityUpdated(object $event): void
    {
        if (method_exists($event, 'getEntity')) {
            $entity = $event->getEntity();

            if ($this->indexingService->shouldAutoIndex($entity)) {
                $this->indexingService->updateEntity($entity);
            }
        }
    }

    /**
     * Handle entity deletion events
     */
    #[EventListener(event: 'entity.deleted')]
    public function onEntityDeleted(object $event): void
    {
        if (method_exists($event, 'getEntity')) {
            $entity = $event->getEntity();

            if ($this->indexingService->shouldAutoIndex($entity)) {
                $this->indexingService->removeEntity($entity);
            }
        }
    }

    /**
     * Handle bulk entity operations
     */
    #[EventListener(event: 'entities.bulk_created')]
    public function onBulkEntitiesCreated(object $event): void
    {
        if (method_exists($event, 'getEntities')) {
            $entities = $event->getEntities();

            // Filter only auto-indexable entities
            $searchableEntities = array_filter(
                $entities,
                fn ($entity) => $this->indexingService->shouldAutoIndex($entity)
            );

            if (! empty($searchableEntities)) {
                $this->indexingService->bulkIndexEntities($searchableEntities);
            }
        }
    }
}
