function xsrfToken(): string | undefined {
  const token = document.cookie
    .split('; ')
    .find((cookie) => cookie.startsWith('XSRF-TOKEN='))
    ?.slice('XSRF-TOKEN='.length);

  return token ? decodeURIComponent(token) : undefined;
}

/**
 * A JSON request to the media endpoints (the picker works outside Inertia visits).
 */
export async function mediaRequest<T>(
  url: string,
  options: RequestInit = {},
): Promise<T> {
  const headers = new Headers(options.headers);
  headers.set('Accept', 'application/json');
  headers.set('X-Requested-With', 'XMLHttpRequest');
  const token = xsrfToken();
  if (token) headers.set('X-XSRF-TOKEN', token);

  const response = await fetch(url, {
    credentials: 'same-origin',
    ...options,
    headers,
  });

  if (!response.ok) {
    const body = (await response.json().catch(() => null)) as {
      message?: string;
    } | null;

    throw new Error(body?.message ?? 'The files are unavailable right now.');
  }

  return response.json() as Promise<T>;
}
