(function () {
  if (globalThis.__AUTH_GUARD_INSTALLED__) {
    return;
  }
  globalThis.__AUTH_GUARD_INSTALLED__ = true;

  if (typeof globalThis.fetch !== "function") {
    return;
  }

  const originalFetch = globalThis.fetch.bind(globalThis);

  function buildFallbackLoginUrl() {
    const current = `${globalThis.location.pathname}${globalThis.location.search}`;
    return `/login?next=${encodeURIComponent(current)}`;
  }

  async function extractLoginUrl(response) {
    try {
      const contentType = response.headers.get("content-type") || "";
      if (!contentType.toLowerCase().includes("application/json")) {
        return "";
      }
      const payload = await response.clone().json();
      if (!payload || payload.code !== "auth_expired") {
        return "";
      }
      return String(payload.login_url || "").trim();
    } catch (_) {
      return "";
    }
  }

  globalThis.fetch = async function guardedFetch(input, init) {
    const options = init ? { ...init } : {};
    const headers = new Headers(options.headers || {});
    if (!headers.has("X-Requested-With")) {
      headers.set("X-Requested-With", "fetch");
    }
    options.headers = headers;
    if (!options.credentials) {
      options.credentials = "same-origin";
    }

    const response = await originalFetch(input, options);
    if (response.status !== 401) {
      return response;
    }

    const loginUrl = (await extractLoginUrl(response)) || buildFallbackLoginUrl();
    globalThis.location.assign(loginUrl);
    const authError = new Error("AUTH_EXPIRED");
    authError.code = "auth_expired";
    throw authError;
  };
})();
