<?php

namespace App\Console\Commands;

use App\Facades\Settings;
use App\VehicleSpec\Services\CapIdCacheBackfillService;
use Illuminate\Console\Command;
use Mtc\MercuryDataModels\Vehicle;

class BackfillModelIdFromCapIdCache extends Command
{
    protected $signature = 'vehicles:backfill-model-id-from-cap-cache {--dry-run : Report what would change without writing}';

    protected $description = 'Backfill model_id for vehicles that have a cap_id but no model_id, using the cap_id_cache.';

    public function handle(CapIdCacheBackfillService $backfill): int
    {
        if ($this->skipForTenant()) {
            return self::SUCCESS;
        }

        $dryRun = (bool) $this->option('dry-run');

        $checked = 0;
        $backfilled = 0;
        $noMatch = 0;

        Vehicle::query()
            ->whereNotNull('cap_id')
            ->where('cap_id', '!=', '')
            ->whereNull('model_id')
            ->chunkById(200, function ($vehicles) use ($backfill, $dryRun, &$checked, &$backfilled, &$noMatch) {
                foreach ($vehicles as $vehicle) {
                    $checked++;

                    if ($backfill->backfillVehicle($vehicle, $dryRun)) {
                        $backfilled++;
                    } else {
                        $noMatch++;
                    }
                }
            });

        $this->info(sprintf(
            '%sChecked %d vehicle(s) with a cap_id and no model_id: %d backfilled, %d without a cache match.',
            $dryRun ? '[dry-run] ' : '',
            $checked,
            $backfilled,
            $noMatch
        ));

        return self::SUCCESS;
    }

    private function skipForTenant(): bool
    {
        // The cap_id_cache is populated independently of the CAP provider (e.g. via
        // HPI lookups), so this backfill only depends on the local cache being enabled
        // — not on vehicle-spec-providers-cap-enabled.
        if (!Settings::get('cap-id-lookup-local-cache-enabled')) {
            $this->info('CAP ID local cache is not enabled for this tenant — skipping backfill.');
            return true;
        }

        return false;
    }
}
