<?php

namespace App\Console\Commands;

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

class BackfillBodyTypeFromCapSector extends Command
{
    protected $signature = 'cap:backfill-body-type-from-sector';

    protected $description = 'Re-derive vehicle body type from CAP sector data for all vehicles with a known CAP ID.';

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

        $updated = 0;
        $checked = 0;

        Vehicle::query()
            ->whereNotNull('cap_id')
            ->where('cap_id', '!=', '')
            ->chunkById(200, function ($vehicles) use ($applier, &$updated, &$checked) {
                foreach ($vehicles as $vehicle) {
                    $checked++;
                    if ($applier->applyForVehicle($vehicle)) {
                        $updated++;
                    }
                }
            });

        $this->info(sprintf('Checked %d vehicles, updated %d body types from CAP sector.', $checked, $updated));

        return self::SUCCESS;
    }

    private function skipForTenant(): bool
    {
        if (!Settings::get('vehicle-spec-providers-cap-enabled')) {
            $this->info('CAP is not enabled for this tenant — skipping backfill.');
            return true;
        }

        if (!Settings::get('vehicle-spec-providers-cap-use-sector-for-body-type')) {
            $this->info('CAP sector body type override is not enabled for this tenant — skipping backfill.');
            return true;
        }

        return false;
    }
}
