<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Collection;
use Mtc\MercuryDataModels\CarConfiguratorModel;
use Mtc\MercuryDataModels\CarConfiguratorSection;

class AllConfiguratorSectionsCompleted implements ValidationRule
{
    private Collection $missingSections;

    public function __construct(private readonly CarConfiguratorModel $model)
    {
        //
    }

    /**
     * Run the validation rule.
     *
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if ($this->hasSectionsMissingSelections($value)) {
            $fail('Not all configuration steps are completed: ' . $this->missingSections->pluck('name')->implode(', '));
        }
    }

    private function hasSectionsMissingSelections(array $value): bool
    {
        $this->missingSections = $this->model->activeSections
            ->filter(fn($section) => empty($section->data['optional']))
            ->reject(fn($section) => $this->sectionIsFilledInRequest($section, $value));

        return $this->missingSections->isNotEmpty();
    }

    private function sectionIsFilledInRequest(CarConfiguratorSection $entry, array $value): bool
    {
        $section = array_filter($value, fn($item) => $item['id'] == $entry->id);
        $section = reset($section);
        return $section && !empty($section['selected']);
    }
}
