<?php

namespace App\Rules;

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

class HasNoDuplicateEquipment implements ValidationRule
{
    use FindsDuplicates;

    /**
     * Run the validation rule.
     *
     * Mirrors the vehicle_standard_equipment unique indexes: within a single save the
     * vehicle is fixed, so equipment 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 ? 'item' : 'items';

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