<?php

namespace App\Console\Commands;

use App\Facades\Settings;
use App\VehicleSpec\Jobs\ApplyCapSectorBodyType;
use Illuminate\Console\Command;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Mtc\MercuryDataModels\Vehicle;

class BackfillBodyTypeFromCapSector extends Command
{
    use DispatchesJobs;

    protected $signature = 'cap:backfill-body-type-from-sector';

    protected $description = 'Queue an ApplyCapSectorBodyType job for every vehicle with a CAP ID so their body type is re-derived from CAP sector data.';

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

        $dispatched = 0;

        Vehicle::query()
            ->whereNotNull('cap_id')
            ->where('cap_id', '!=', '')
            ->chunkById(100, function ($vehicles) use (&$dispatched) {
                foreach ($vehicles as $vehicle) {
                    $this->dispatch(new ApplyCapSectorBodyType($vehicle));
                    $dispatched++;
                }
            });

        $this->info(sprintf('Queued %d ApplyCapSectorBodyType jobs on the specs queue.', $dispatched));

        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;
    }
}
