<?php

namespace App\Console\Commands;

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

class LookupCapIdForVehicles extends Command
{
    use DispatchesJobs;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'vehicles:cap-id-lookup';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Find CAP ID for vehicles without one';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        if ($this->skipForTenant()) {
            return self::SUCCESS;
        }

        Vehicle::query()
            ->whereNull('cap_id')
            ->chunk(200, function (Collection $chunk) {
                $chunk->each(fn (Vehicle $vehicle) => $this->dispatch(new VehicleCapIdLookup($vehicle)));
            });
        return self::SUCCESS;
    }

    private function skipForTenant(): bool
    {
        return !Settings::get('vehicle-spec-providers-cap-enabled')
            || !Settings::get('vehicle-spec-providers-cap-repeated-checks');
    }
}
