<?php

namespace App\Rules;

use Illuminate\Support\Collection;

trait FindsDuplicates
{
    /**
     * Return the display values that appear more than once for the given key.
     *
     * Comparison is case-insensitive and ignores surrounding whitespace to match the
     * collation used by the vehicle data unique indexes. Blank values are skipped: the
     * `required` rules reject them separately and the database stores them as distinct
     * NULLs. The first occurrence is kept so the message shows the admin's own wording.
     *
     * @return \Illuminate\Support\Collection<int, string>
     */
    private function duplicateValues(mixed $items, string $key): Collection
    {
        return collect($items)
            ->map(fn ($item) => trim((string) data_get($item, $key)))
            ->reject(fn (string $value) => $value === '')
            ->groupBy(fn (string $value) => mb_strtolower($value))
            ->filter(fn (Collection $group) => $group->count() > 1)
            ->map(fn (Collection $group) => $group->first())
            ->values();
    }
}
