<?php

namespace App\Jobs;

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\Colour;
use Mtc\MercuryDataModels\ColourMap;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleOffer;

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

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $colours = Colour::all();
        Vehicle::query()
            ->distinct()
            ->whereDoesntHave('colourMap')
            ->pluck('colour')
            ->each(fn ($vehicleColour) => $this->mapColour($vehicleColour, $colours));
        VehicleOffer::query()
            ->distinct()
            ->whereDoesntHave('colourMap')
            ->pluck('colour')
            ->each(fn ($vehicleColour) => $this->mapColour($vehicleColour, $colours));
    }

    private function mapColour(?string $vehicleColour, Collection $colours): void
    {
        if (empty($vehicleColour)) {
            return;
        }
        $match = $colours->filter(fn ($colour) => stripos($vehicleColour, (string) $colour->colour) !== false)->first();

        if ($match) {
            ColourMap::query()
                ->create([
                    'colour_id' => $match->id,
                    'sub_colour' => $vehicleColour,
                ]);
        }
    }
}
