<?php

namespace App\Observers;

use App\VehicleSpec\Services\CapIdCacheBackfillService;
use Mtc\MercuryDataModels\CapIdCache;

class CapIdCacheObserver
{
    public function __construct(private CapIdCacheBackfillService $backfill)
    {
    }

    /**
     * When a cache row is created or updated to carry a matched model value,
     * backfill any vehicles that share its cap_id but have no model_id yet.
     */
    public function saved(CapIdCache $capIdCache): void
    {
        if (empty($capIdCache->cap_id) || empty($capIdCache->cap_matched_model_id)) {
            return;
        }

        if (!$capIdCache->wasRecentlyCreated && !$capIdCache->wasChanged('cap_matched_model_id')) {
            return;
        }

        $this->backfill->backfillForCapId((string) $capIdCache->cap_id);
    }
}
