<?php

declare(strict_types=1);

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);
    }
}
