<?php

namespace App;

use Illuminate\Support\Collection;
use Mtc\MercuryDataModels\Colour;
use Mtc\MercuryDataModels\ColourMap;

class ColourMapRepository
{
    public function update(array $colours)
    {
        $this->removeMissing(collect($colours)->pluck('id'));
        collect($colours)
            ->each(fn (array $colourData) => $this->saveColourData($colourData));
    }

    private function saveColourData(array $colourData): void
    {
        /** @var Colour $colour */
        $colour = Colour::query()
            ->updateOrCreate([
                'id' => $colourData['id'],
            ], [
                'colour' => $colourData['colour'],
                'hex_code' => $colourData['hex_code'],
                'gradient_hex_code' => $colourData['gradient_hex_code'] ?? null,
            ]);

        $colour->mappedColours()
            ->whereNotIn('sub_colour', collect($colourData['subColours'])->pluck('name')->toArray())
            ->delete();

        if (!empty($colourData['subColours'])) {
            $values = collect($colourData['subColours'])
                ->map(fn ($subColour) => [
                    'colour_id' => $colour->id,
                    'sub_colour' => $subColour['name'],
                ])
                ->toArray();
            $colour->mappedColours()->upsert($values, ['colour_id', 'sub_colour']);
        }
    }

    private function removeMissing(Collection $ids): void
    {
        $toRemove = Colour::query()
            ->whereNotIn('id', $ids)
            ->pluck('id');

        if ($toRemove->isNotEmpty()) {
            Colour::query()
                ->whereIn('id', $toRemove)
                ->delete();

            ColourMap::query()
                ->whereIn('colour_id', $toRemove)
                ->delete();
        }
    }
}
