export function jsonHeaders(): Record<string, string> {
    const match = document.cookie.match(/XSRF-TOKEN=([^;]+)/);

    return {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
        ...(match ? { 'X-XSRF-TOKEN': decodeURIComponent(match[1]) } : {}),
    };
}

/**
 * POST d’une action `redirect` (SSO cPanel, etc.). Ouvre l’onglet tout de suite
 * pour rester dans le geste utilisateur, puis y place l’URL `Inertia::location`.
 */
export async function openProvisionerRedirect(
    url: string,
    payload: Record<string, unknown> = {},
): Promise<boolean> {
    const tab = window.open('about:blank', '_blank');

    if (tab) {
        tab.opener = null;
    }

    const response = await fetch(url, {
        method: 'POST',
        credentials: 'same-origin',
        redirect: 'manual',
        headers: {
            ...jsonHeaders(),
            'X-Inertia': 'true',
        },
        body: JSON.stringify(payload),
    });

    const location =
        response.headers.get('X-Inertia-Location') ??
        response.headers.get('Location');

    if (!location) {
        tab?.close();

        return false;
    }

    if (tab) {
        tab.location.href = location;

        return true;
    }

    window.location.assign(location);

    return true;
}
