<?php

namespace App\Listeners;

use App\Events\VehicleUpdatedFromImport;
use App\Services\MeilisearchService;
use Mtc\MercuryDataModels\Vehicle;

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

    /**
     * Remove a vehicle from the Meilisearch index when an import marks it deleted.
     *
     * Stock-sync deletions can set deleted_at via a fill+save (rather than a model
     * delete) and bypass the per-vehicle indexer, leaving orphaned documents that
     * inflate result counts. This handles the case where an import has just
     * soft-deleted the vehicle, regardless of provider.
     */
    public function handle(VehicleUpdatedFromImport $event): void
    {
        if (!$this->meilisearchService->isEnabled()) {
            return;
        }

        /** @var Vehicle $vehicle */
        $vehicle = $event->vehicle;

        if (!$vehicle->wasChanged('deleted_at') || empty($vehicle->deleted_at)) {
            return;
        }

        $this->meilisearchService->deleteVehicle($vehicle->id);
    }
}
