<?php

namespace App\Listeners;

use App\Events\NewVehicleImported;
use App\Events\VehicleUpdatedFromImport;
use App\Services\MeilisearchService;

class IndexVehicleInMeilisearch
{
    /**
     * Providers that use notifications and should index vehicles individually.
     */
    private const NOTIFICATION_PROVIDERS = [
        'autograb',
        'auto-trader-hub',
    ];

    public function __construct(private readonly MeilisearchService $meilisearchService)
    {
    }

    /**
     * Handle vehicle imported/updated events.
     *
     * Only processes vehicles from notification-based providers (AutoTrader Hub, AutoGrab).
     * Batch stock providers handle indexing via StockSyncFinished event.
     */
    public function handle(NewVehicleImported|VehicleUpdatedFromImport $event): void
    {
        if (!$this->meilisearchService->isEnabled()) {
            return;
        }

        // Only index vehicles from notification-based providers
        if (!in_array($event->provider, self::NOTIFICATION_PROVIDERS, true)) {
            return;
        }

        $this->meilisearchService->indexVehicle($event->vehicle);
    }
}
