<?php

namespace App\Rules;

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

class HasNoDuplicateEquipment implements ValidationRule
{
    /**
     * Run the validation rule.
     *
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if ($this->hasDuplicates($value)) {
            $fail('There are duplicate equipment items, they should have unique descriptions');
        }
    }

    private function hasDuplicates(mixed $value): bool
    {
        // Mirror the vehicle_standard_equipment unique index (vehicle_id + vehicle_type + description).
        // Within a single save vehicle_id/vehicle_type are constant, so descriptions must be unique.
        // Normalise to match the column's case-insensitive, trailing-space-insensitive collation,
        // and ignore blank descriptions which the DB treats as distinct NULLs.
        $descriptions = collect($value)
            ->pluck('description')
            ->map(fn ($description) => mb_strtolower(trim((string) $description)))
            ->filter();

        return $descriptions->unique()->count() < $descriptions->count();
    }
}
