<?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',
    ];

    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
    {
        // Disabled or listing site. Listing sites will have too high volume, therefore indexes via scheduler
        if (!$this->meilisearchService->isEnabled() || tenant('type') === 'listing') {
            return;
        }

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

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