<?php

namespace App\Jobs;

use App\Services\Pyxel;
use App\Traits\ImportChecksConditions;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Mtc\MercuryDataModels\Dealership;
use Mtc\MercuryDataModels\Vehicle;

class ImportPyxelVehicleImagesJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;
    use ImportChecksConditions;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(private readonly Pyxel $service)
    {
        $this->onQueue('bulk-media');
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(): void
    {
        Dealership::all()
            ->filter(fn(Dealership $dealership) => !empty($dealership->data['pyxel-dealership']))
            ->each(fn(Dealership $dealership) => $this->processImagesForLocation($dealership));
    }

    private function processImagesForLocation(Dealership $dealership): void
    {
        $resultData = collect($this->service->getVehicleMedia($dealership->data['pyxel-dealership']))->keyBy('vrm');

        Vehicle::query()
            ->whereIn('vrm_condensed', $resultData->pluck('vrm'))
            ->get()
            ->each(fn(Vehicle $vehicle) => $this->processVehicleData($vehicle, $resultData[$vehicle->vrm_condensed]));
    }

    private function processVehicleData(Vehicle $vehicle, $vehicle_data): void
    {
        if (!empty($vehicle_data['imageUrls']) && $this->imageChecksumMismatch($vehicle_data['imageUrls'], $vehicle)) {
            ImportImagesFromUrlList::dispatch(collect($vehicle_data['imageUrls']), $vehicle, false, 'pyxel');
        }

        if (!empty($vehicle_data['webVideoIds'])) {
            $vehicle->update([
                'main_video_url' => $vehicle_data['webVideoIds'][0]
            ]);
        }
    }
}
