<?php

declare(strict_types=1);

namespace App\Filament\Support;

use Illuminate\Database\Eloquent\Builder;

/**
 * 为 Filament relationship Select 提供「空搜索时限量预载」的查询约束，
 * 避免在超大表上一次性加载全部关联记录，同时保持可搜索。
 */
final class DberpFilamentRelationshipSelectLimits
{
    /** 可搜索下拉在空搜索/预载时返回的最大选项数（与商品/规格搜索预载一致）。 */
    public const PRELOAD_OPTION_LIMIT = 100;

    public static function limitProductOptionsQuery(Builder $query, ?string $search): Builder
    {
        if (! filled($search)) {
            $query
                ->orderBy($query->qualifyColumn('sort_order'))
                ->orderBy($query->qualifyColumn('id'))
                ->limit(self::PRELOAD_OPTION_LIMIT);
        }

        return $query;
    }

    public static function limitInventoryBatchOptionsQuery(Builder $query, ?string $search): Builder
    {
        if (! filled($search)) {
            $query->orderByDesc($query->qualifyColumn('id'))->limit(self::PRELOAD_OPTION_LIMIT);
        }

        return $query;
    }

    public static function limitInventorySerialNumberOptionsQuery(Builder $query, ?string $search): Builder
    {
        if (! filled($search)) {
            $query
                ->orderBy($query->qualifyColumn('sort_order'))
                ->orderBy($query->qualifyColumn('id'))
                ->limit(self::PRELOAD_OPTION_LIMIT);
        }

        return $query;
    }
}
