<?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\KeyloopLeaseColour;
use Mtc\MercuryDataModels\VehicleMake;

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

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

    /**
     * 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()
            ->chunkById(50, function (Collection $colours) use ($make) {
                // get the colour data for this group of colours
                $colours_data = (new ImaginStudioApi())->getColourData(
                    $colours->pluck('colour_code'),
                    $make->name ?? '',
                );

                $colours->each(function ($colour) use ($colours_data) {
                    $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),
                        ]);
                    }
                });
            });
    }
}
