<?php

namespace App\Listeners;

use App\Events\StockSyncFinished;
use App\Services\MeilisearchService;

class SyncVehiclesToMeilisearch
{
    /**
     * Providers that handle individual vehicle indexing via notifications
     * and should be skipped for batch sync.
     */
    private const NOTIFICATION_PROVIDERS = [
        'autograb',
        'auto-trader-hub',
    ];

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

    /**
     * Handle the stock sync finished event.
     *
     * Triggers a full Meilisearch reindex for batch stock providers.
     * Notification-based providers (AutoTrader Hub, AutoGrab) are skipped
     * as they handle indexing per-vehicle via NewVehicleImported/VehicleUpdatedFromImport events.
     */
    public function handle(StockSyncFinished $event): void
    {
        if (!$this->meilisearchService->isEnabled()) {
            return;
        }

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

        $this->meilisearchService->syncAllVehicles();
    }
}
