import { router, usePage } from '@inertiajs/vue3';
import { computed, type ComputedRef } from 'vue';

/**
 * Apply list filters through the query string, as the Blade pages did (?search=, ?status=).
 * Empty values are dropped and the page resets to 1, since the old page number rarely exists in
 * the new result.
 */
export function applyFilters(filters: Record<string, string | null | undefined>, options: { only?: string[] } = {}): void {
    const query = Object.fromEntries(new URLSearchParams(window.location.search));
    delete query.page;
    for (const [key, value] of Object.entries(filters)) {
        if (value === null || value === undefined || value === '') {
            delete query[key];
        } else {
            query[key] = value;
        }
    }

    router.get(window.location.pathname, query, {
        preserveState: true,
        preserveScroll: true,
        replace: true,
        only: options.only,
    });
}

/** One query-string value of the current page, kept in step with Inertia visits. */
export function useQueryValue(key: string, fallback = ''): ComputedRef<string> {
    const page = usePage();

    return computed(() => new URL(page.url, window.location.origin).searchParams.get(key) ?? fallback);
}
