import { createSignal } from 'solid-js';

// Shared across the admin app: set to true the moment any authenticated request
// comes back 401, so a single dialog (mounted in AdminShell) can tell the admin
// their session expired instead of pages failing silently one by one.
const [sessionExpired, setSessionExpired] = createSignal(false);

export { sessionExpired };

export function markSessionExpired(): void {
  setSessionExpired(true);
}

export function clearSessionExpired(): void {
  setSessionExpired(false);
}

let patched = false;

/**
 * Wrap window.fetch once so any authenticated admin request that comes back 401
 * flips the shared session-expired signal, regardless of which page/helper made
 * the call. Idempotent — safe to call from every AdminShell mount.
 */
export function installSessionExpiryWatcher(): void {
  if (patched || typeof window === 'undefined') return;
  patched = true;

  const originalFetch = window.fetch.bind(window);
  window.fetch = async (...args: Parameters<typeof fetch>) => {
    const response = await originalFetch(...args);
    if (response.status === 401) {
      const hadToken =
        typeof sessionStorage !== 'undefined' &&
        Boolean(sessionStorage.getItem('nxtgauge_admin_access_token'));
      // Only treat this as a session expiry if we were actually holding a token —
      // otherwise this is just a normal pre-login 401 (e.g. a failed login attempt).
      if (hadToken) markSessionExpired();
    }
    return response;
  };
}
