const AUTH_TOKEN_STORAGE_KEY = 'easyai_ai_gateway_access_token';
const OIDC_SESSION_TOKEN_STORAGE_KEY = 'easyai_ai_gateway_oidc_access_token';

export function readStoredAccessToken() {
  if (typeof window === 'undefined') return '';
  try {
    // Remove credentials written by the retired browser-token implementation.
    window.sessionStorage.removeItem(OIDC_SESSION_TOKEN_STORAGE_KEY);
    return window.localStorage.getItem(AUTH_TOKEN_STORAGE_KEY) ?? '';
  } catch {
    return '';
  }
}

export function persistAccessToken(value: string) {
  if (typeof window === 'undefined') return;
  try {
    if (!value) {
      window.localStorage.removeItem(AUTH_TOKEN_STORAGE_KEY);
      window.sessionStorage.removeItem(OIDC_SESSION_TOKEN_STORAGE_KEY);
    } else {
      window.sessionStorage.removeItem(OIDC_SESSION_TOKEN_STORAGE_KEY);
      window.localStorage.setItem(AUTH_TOKEN_STORAGE_KEY, value);
    }
  } catch {
    // Ignore storage failures so private browsing or quota issues do not break login.
  }
}
