<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Support;

use App\Filament\Resources\DberpDocumentQueries\DberpDocumentQueryResource;

final class DberpDocumentQueryFilamentSupport
{
    /**
     * @param  array<string, mixed>  $state
     * @param  array<string, mixed>  $overrides
     * @return array<string, mixed>
     */
    public static function buildTableFiltersFromAnalysisState(array $state, array $overrides = []): array
    {
        $filters = [];

        if (! empty($state['business_time_from']) || ! empty($state['business_time_until'])) {
            $filters['business_time'] = array_filter([
                'from' => $state['business_time_from'] ?? null,
                'until' => $state['business_time_until'] ?? null,
            ]);
        }

        foreach (['customer_id', 'supplier_id', 'warehouse_id', 'handler_employee_id'] as $key) {
            if (! empty($state[$key])) {
                $filters[$key] = ['value' => (int) $state[$key]];
            }
        }

        if (! empty($state['status'])) {
            $filters['status'] = ['value' => (string) $state['status']];
        }

        foreach ($overrides as $key => $value) {
            if ($value === null || $value === '') {
                unset($filters[$key]);

                continue;
            }

            if (in_array($key, ['customer_id', 'supplier_id', 'warehouse_id', 'handler_employee_id', 'document_type', 'status'], true)) {
                $filters[$key] = ['value' => $value];

                continue;
            }

            $filters[$key] = $value;
        }

        return $filters;
    }

    /**
     * @param  array<string, mixed>  $tableFilters
     */
    public static function indexUrl(array $tableFilters = []): string
    {
        $base = DberpDocumentQueryResource::getUrl('index');

        if ($tableFilters === []) {
            return $base;
        }

        return DberpFilamentListPageUrl::append($base, $tableFilters);
    }
}
