/**
 * JSON requests to the app's own endpoints that are not Inertia visits (estimates, lookups).
 * Laravel sets the XSRF-TOKEN cookie on every response and accepts it back as X-XSRF-TOKEN.
 */
function xsrfToken(): string {
    const match = document.cookie.match(/(?:^|;\s*)XSRF-TOKEN=([^;]+)/);

    return match ? decodeURIComponent(match[1]) : '';
}

export async function postJson<T>(url: string, body: Record<string, unknown>): Promise<{ ok: boolean; status: number; data: T }> {
    const response = await fetch(url, {
        method: 'POST',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest',
            'X-XSRF-TOKEN': xsrfToken(),
        },
        body: JSON.stringify(body),
    });

    return { ok: response.ok, status: response.status, data: (await response.json().catch(() => null)) as T };
}

