<?php

namespace App\Console\Commands;

use App\Jobs\LookupAutoGrabVehicleId;
use App\Master\Models\CapVehicle;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;

class LookupAutoGrabVehicleIds extends Command
{
    protected $signature = 'cap-vehicles:autograb-lookup';

    protected $description = 'Lookup AutoGrab vehicle IDs for CAP vehicles without one';

    public function handle(): int
    {
        if (empty(config('services.autograb.api_key'))) {
            $this->error('AutoGrab API key not configured.');
            return self::FAILURE;
        }

        $count = CapVehicle::query()->whereDoesntHave('autograbVehicleIds')->count();
        $this->info("Found {$count} CAP vehicles without AutoGrab vehicle ID.");

        CapVehicle::query()
            ->whereDoesntHave('autograbVehicleIds')
            ->chunk(200, function (Collection $chunk) {
                $chunk->each(
                    fn (CapVehicle $vehicle) => LookupAutoGrabVehicleId::dispatch($vehicle)
                );
            });

        $this->info('Jobs dispatched.');

        return self::SUCCESS;
    }
}
