<?php

namespace App\Jobs;

use App\Modules\Stock\AutoTraderStock;
use App\Services\AutoTraderApi;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\App;
use Mtc\AutoTraderStock\Services\AutoTraderService;
use Mtc\MercuryDataModels\Vehicle;

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

    /**
     * Create a new job instance.
     */
    public function __construct(private readonly AutoTraderStock $provider)
    {
        $this->onQueue('sync');
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $this->provider->loadDealerships()
            ->map(fn ($dealership) => new AutoTraderService($dealership, App::make(AutoTraderApi::class))
                ->fetchVehicles())
            ->flatten(1)
            ->each(fn ($vehicle) => $this->updateVehicleId($vehicle));
    }

    private function updateVehicleId(array $vehicle)
    {
        Vehicle::query()
            ->whereNull('auto_trader_id')
            ->where('vrm_condensed', $vehicle['vehicle']['registration'])
            ->update(['auto_trader_id' => $vehicle['metadata']['stockId']]);
    }
}
