// A module-level "current session token" that AuthContext keeps in sync
// (set on restore/sign-in, cleared on sign-out) and authFetch() reads at
// call time. Kept outside React state deliberately: MediaContext and the
// screens that call the backend aren't necessarily re-rendered just
// because the token changes, and a plain fetch wrapper is simpler to drop
// into existing call sites than threading the token through props/context
// everywhere it's needed.
let currentToken: string | null = null;

export function setAuthToken(token: string | null) {
  currentToken = token;
}

/**
 * Drop-in replacement for `fetch()` that attaches the current session's
 * `Authorization: Bearer <token>` header — use this for every call to a
 * backend endpoint that requires a signed-in user (currently `/info`,
 * `/download`, `/status/:jobId`, `/jobs/:jobId`). Static asset requests
 * (e.g. the `/downloads/<file>` route itself) don't need it.
 */
export async function authFetch(url: string, options: RequestInit = {}): Promise<Response> {
  const headers = new Headers(options.headers);
  if (currentToken) headers.set("Authorization", `Bearer ${currentToken}`);
  return fetch(url, { ...options, headers });
}
