const TOKEN_KEY = 'bloby_token';

let authFailureCallback: (() => void) | null = null;

export function getAuthToken(): string | null {
  return localStorage.getItem(TOKEN_KEY);
}

export function setAuthToken(token: string): void {
  localStorage.setItem(TOKEN_KEY, token);
}

export function clearAuthToken(): void {
  localStorage.removeItem(TOKEN_KEY);
}

/** Register a callback for when a 401 is received (token expired mid-session) */
export function onAuthFailure(cb: () => void): void {
  authFailureCallback = cb;
}

export async function authFetch(url: string, options: RequestInit = {}): Promise<Response> {
  const token = getAuthToken();
  const headers = new Headers(options.headers);
  if (token) {
    headers.set('Authorization', `Bearer ${token}`);
  }

  const res = await fetch(url, { ...options, headers });

  if (res.status === 401 && token) {
    // Token was present but rejected — it expired
    clearAuthToken();
    authFailureCallback?.();
  }

  return res;
}
