<?php

namespace App\Jobs;

use App\Facades\Settings;
use App\Services\ImaginStudioApi;
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\Collection;
use Mtc\MercuryDataModels\KeyloopLeaseVehicleVariant;
use Mtc\MercuryDataModels\VehicleMake;

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

    private ImaginStudioApi $api;

    /**
     * Create a new job instance.
     */
    public function __construct()
    {
        $this->onQueue('specs');
        $this->api = new ImaginStudioApi();
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        if (Settings::get('imagin-placeholders-import-colour-enabled') == false) {
            return;
        }

        VehicleMake::query()
            ->whereHas('leaseColours', fn($query) => $query->whereNull('hex_code'))
            ->with('leaseColours')
            ->get()
            ->each(fn(VehicleMake $make) => $this->getColoursForMake($make));
    }

    private function getColoursForMake(VehicleMake $make): void
    {
        $make->leaseColours()
            ->whereNull('hex_code')
            ->chunkById(50, function (Collection $colours) use ($make) {
                // get the colour data for this group of colours
                $colours_data = $this->api->getColourData(
                    $colours->pluck('colour_code'),
                    $make->name ?? '',
                );

                $colours->each(function ($colour) use ($colours_data, $make) {
                    $colour_data = $colours_data['paints'][strtolower($colour->colour_code)] ?? [];
                    $hex = $colour_data['primarySprayCan']['primarySprayCanRGB'] ?? '';
                    $hex_gradient = $colour_data['primarySprayCan']['primarySprayCanHighLightRGB'] ?? '';

                    if ($hex) {
                        $colour->update([
                            'hex_code' => str_replace('#', '', $hex),
                            'gradient_hex_code' => str_replace('#', '', $hex_gradient),
                        ]);
                    } else {
                        // Imagin Studio couldn't provide colour data.
                        // This may be because the colour has never been requested for this manufacturer before.
                        // Request an image with this colour to trigger the Imagin Studio mapping process.
                        // The call MUST include both paint ID and paint description.
                        // After triggering, future colour data calls may return data.
                        $this->api->getVehicleImage(
                            $make->name ?? '',
                            $this->getModelName($make) ?? '',
                            $colour->colour_code ?? '',
                            $colour->name ?? '',
                        );
                    }
                });
            });
    }

    private function getModelName(VehicleMake $make): string
    {
        return KeyloopLeaseVehicleVariant::query()
            ->where('make_id', $make->id)
            ->first()
            ?->model
            ?->name ?? '';
    }
}
