<?php

namespace App\Rules;

use App\Support\ExcelImportHelper;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;

class DuplicateImportColumnsRule implements ValidationRule
{
    public function __construct(
        protected int $headerRowIndex = 0
    ) {}

    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        $file = \Illuminate\Support\Arr::first((array) $value);
        if (! $file instanceof TemporaryUploadedFile) {
            return;
        }
        $path = $file->getRealPath();
        [$headers, ] = ExcelImportHelper::readHeadersAndRows($path, $this->headerRowIndex);
        $counts = array_count_values($headers);
        $dupes = array_keys(array_filter($counts, fn ($c) => $c > 1));
        if (! empty($dupes)) {
            $fail(trans_choice('filament-actions::import.modal.form.file.rules.duplicate_columns', count($dupes), ['columns' => implode(', ', $dupes)]));
        }
    }
}
