<?php

namespace App\Jobs;

use App\Facades\Feature;
use App\Facades\Settings;
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 ($this->shouldUpdateImages($vehicle, $vehicle_data)) {
            ImportImagesFromUrlList::dispatch(collect($vehicle_data['imageUrls']), $vehicle, false, 'pyxel', true);
        }

        if (!empty($vehicle_data['webVideoIds'])) {
            $vehicle->update([
                'main_video_url' => 'https://youtu.be/' . $vehicle_data['webVideoIds'][0]
            ]);
        }
        if (!empty($vehicle_data['threeSixtyData'])) {
            $links = array_filter($vehicle_data['threeSixtyData'], fn($row) => $row['type'] === 'Interior');
            if (!empty($links)) {
                $data = $vehicle->data ?? [];
                $data['interior_video_type'] = 'pyxel';
                preg_match("#306/([0-9]+)/interior#", (string) $links[0]['link'], $matches);
                $videoId = $matches[1] ?? null;
                if ($videoId) {
                    $vehicle->update([
                        'interior_video_url' => "https://dashboard.pyxel.com/admin/306/$videoId.360",
                        'data' => $data,
                    ]);
                }
            }
        }
    }

    private function shouldUpdateImages(Vehicle $vehicle, $vehicle_data): bool
    {
        $imageThreshold = 1;
        if ($this->hasImaginStudioPlaceholders()) {
            $imageThreshold = 3;
        }
        return !empty($vehicle_data['imageUrls'])
            && count($vehicle_data['imageUrls']) >= $imageThreshold
            && $this->imageChecksumMismatch($vehicle_data['imageUrls'], $vehicle);
    }

    private function hasImaginStudioPlaceholders(): bool
    {
        return Feature::isEnabled('imagin-studio-placeholders')
            && Settings::get('imagin-placeholders-vehicle-enabled');
    }
}
