<?php

namespace App\Jobs;

use App\Master\Models\CapVehicle;
use App\Master\Models\CapVehicleAutoGrabId;
use App\Services\AutoGrabVehicleLookupService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class LookupAutoGrabVehicleId implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public int $tries = 3;
    public int $backoff = 60;

    public function __construct(protected CapVehicle $vehicle)
    {
        $this->onQueue('motors-batch');
    }

    public function handle(AutoGrabVehicleLookupService $service): void
    {
        $vehicleIds = $service->getVehicleIds($this->vehicle);

        foreach ($vehicleIds as $vehicleId) {
            CapVehicleAutoGrabId::query()->firstOrCreate(
                ['autograb_vehicle_id' => $vehicleId],
                ['cap_vehicle_id' => $this->vehicle->id]
            );
        }
    }
}
