/**
 * One-shot login-redirect helper.
 *
 * Problem: the OIDC guard issues a 302 to Authelia, but fetch()/XHR cannot follow a
 * cross-origin 302 to Authelia — the browser enforces CORS on XHR redirects, so the
 * response is opaque and the SPA never reaches Authelia. Re-auth requires a TOP-LEVEL
 * browser navigation to /api/login, where the guard's redirect is followed at the
 * document level (no CORS restriction).
 *
 * Solution: when /api/me fails (indicating an unauthenticated session), perform a
 * full-page navigation to /api/login. A sessionStorage flag prevents infinite loops:
 * if the navigation completes and /api/me still fails (genuine error), the second
 * maybeRedirectToLogin() call is a no-op and the "Sign-in required" UI is shown.
 */

export const LOGIN_REDIRECT_KEY = 'familysync.loginRedirectAttempted';

/**
 * Navigate to /api/login if this is the first attempt.
 *
 * Returns true when a redirect was triggered (caller can bail early — the page
 * is navigating away). Returns false when the flag was already set (already
 * bounced through login once; let the caller render the error UI instead).
 *
 * Safe under SSR/test environments: no-ops and returns false when window or
 * sessionStorage is unavailable.
 */
export function maybeRedirectToLogin(): boolean {
  if (typeof window === 'undefined') return false;
  if (typeof sessionStorage === 'undefined') return false;

  try {
    if (sessionStorage.getItem(LOGIN_REDIRECT_KEY) !== null) {
      // Already attempted — do not redirect again (loop guard).
      return false;
    }
    sessionStorage.setItem(LOGIN_REDIRECT_KEY, '1');
    window.location.href = '/api/login';
    return true;
  } catch {
    // sessionStorage access can throw in private-browsing mode or with storage quota
    // exceeded. Fail open: do not redirect, let the caller render the error.
    return false;
  }
}

/**
 * Clear the one-shot flag.
 *
 * Call on a successful /api/me load so that a later session expiry can trigger
 * another redirect instead of silently showing "Sign-in required".
 *
 * Safe under SSR/test environments (guarded).
 */
export function clearLoginRedirect(): void {
  if (typeof window === 'undefined') return;
  if (typeof sessionStorage === 'undefined') return;

  try {
    sessionStorage.removeItem(LOGIN_REDIRECT_KEY);
  } catch {
    // Ignore storage errors — clearing the flag is best-effort.
  }
}
