<?php

declare(strict_types=1);

namespace App\Support;

use Closure;
use Filament\Forms\Components\Select;

/**
 * Filament 可搜索下拉：数量较少时打开即展示全部选项；超过阈值时预载有限条并支持远程搜索。
 */
final class DberpFilamentSearchableSelectOptions
{
    /**
     * @param  Closure(): int  $resolveOptionCount
     * @param  Closure(): array<int|string, string>  $resolveAllOptions
     * @param  Closure(string): array<int|string, string>  $resolveSearchOptions
     * @param  Closure(mixed): ?string|null  $resolveOptionLabel
     */
    public static function configure(
        Select $field,
        Closure $resolveOptionCount,
        Closure $resolveAllOptions,
        Closure $resolveSearchOptions,
        ?Closure $resolveOptionLabel = null,
    ): Select {
        $field = $field->searchable();

        if ($resolveOptionLabel !== null) {
            $field->getOptionLabelUsing($resolveOptionLabel);
        }

        if ($resolveOptionCount() < DberpProductSkuSelectOptions::SEARCHABLE_OPTION_THRESHOLD) {
            return $field
                ->options($resolveAllOptions)
                ->preload();
        }

        return $field
            ->options(fn (): array => $resolveSearchOptions(''))
            ->getSearchResultsUsing(fn (string $search): array => $resolveSearchOptions($search))
            ->preload();
    }
}
