/* eslint-disable no-restricted-globals */
/**
 * Inline snippet that patches fetch and XMLHttpRequest to automatically
 * include the CSRF session token header on every request to the dev server.
 *
 * Values are injected at compile time via esbuild `define`:
 *   - process.env.SESSION_TOKEN  → the generated token string
 *   - process.env.SESSION_HEADER → the custom header name
 */

const token: string | undefined = process.env.SESSION_TOKEN;
const header: string | undefined = process.env.SESSION_HEADER;

// Patch fetch
const originalFetch = window.fetch;
window.fetch = function (
  input: RequestInfo | URL,
  init?: RequestInit,
): Promise<Response> {
  // Seed the headers from init.headers when provided, otherwise from the
  // headers already set on a Request `input`. Building from `init.headers`
  // alone would discard a Request's own headers (e.g. Content-Type) because
  // passing a fresh `init.headers` to fetch() replaces the input's headers
  // entirely
  const headers = new Headers(
    init?.headers ?? (input instanceof Request ? input.headers : undefined),
  );
  headers.set(header!, token!);
  return originalFetch.call(this, input, { ...init, headers });
};

// Patch XMLHttpRequest
const originalSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function (
  body?: Document | XMLHttpRequestBodyInit | null,
) {
  this.setRequestHeader(header!, token!);
  return originalSend.call(this, body);
};
