/**
 * Auth state — access + refresh tokens.
 *
 * Storage:
 *   - access token: in-memory (XSS-safe). Never persisted to
 *     localStorage / sessionStorage.
 *   - refresh token: httpOnly + Secure + SameSite=Lax cookie set by
 *     authd. JS cannot read it (which is the point).
 *
 * On page reload, we lose the access token. The /v1/auth/me call
 * on app boot triggers a refresh-if-needed via the refresh cookie,
 * and the response gives us a fresh access token. If refresh
 * fails, we redirect to /login.
 */

let accessToken: string | null = null;
let refreshToken: string | null = null;
let lastRefreshFailureUrl: string | null = null;

export interface TokenPair {
  access: string;
  refresh: string;
}

export function setTokens(pair: TokenPair): void {
  accessToken = pair.access;
  refreshToken = pair.refresh;
}

export function setAccessToken(access: string): void {
  accessToken = access;
}

export function clearTokens(): void {
  accessToken = null;
  refreshToken = null;
}

export function getAccessToken(): string | null {
  return accessToken;
}

export function getRefreshToken(): string | null {
  // The refresh cookie is sent automatically via credentials:'include'.
  // JS never reads it directly.
  return refreshToken;
}

export function markRefreshFailure(fromUrl: string): void {
  lastRefreshFailureUrl = fromUrl;
}

export function getRefreshFailureUrl(): string | null {
  return lastRefreshFailureUrl;
}
