<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Collection;

class HasNoDuplicateSpecs implements ValidationRule
{
    use FindsDuplicates;

    /**
     * Run the validation rule.
     *
     * Mirrors the vehicle_tech_data unique indexes: within a single save the vehicle is
     * fixed, so technical specification descriptions must be unique.
     *
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        $duplicates = $this->duplicateValues($value, 'description');

        if ($duplicates->isNotEmpty()) {
            $fail($this->message($duplicates));
        }
    }

    private function message(Collection $duplicates): string
    {
        $items = $duplicates->map(fn (string $description) => '"' . $description . '"')->implode(', ');
        $noun = $duplicates->count() === 1 ? 'specification' : 'specifications';

        return "Duplicate technical {$noun} {$items}: each specification must have a unique description.";
    }
}
