<?php

namespace App\Rules;

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

class HasNoDuplicateFeatures implements ValidationRule
{
    use FindsDuplicates;

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

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

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

        return "Duplicate {$noun} {$items}: each feature must have a unique name.";
    }
}
