// frontend/src/api.ts
import 'tus-js-client'

declare module 'tus-js-client' {
  interface UploadOptions {
    withCredentials?: boolean
  }
}

/** Issue an authenticated fetch against the Pegasus API and normalize the response body. */
export async function api<T=any>(path: string, init?: RequestInit): Promise<T> {
  const r = await fetch(path, { credentials:'include', ...init });
  if (!r.ok) throw new Error(await r.text());
  const ct = r.headers.get('content-type') || '';
  if (ct.includes('json')) return r.json() as Promise<T>;
  const txt = await r.text();
  try { return JSON.parse(txt) as T } catch { return txt as any as T }
}

/** WHOAMI payload returned by the backend and kept backward-compatible during migration. */
export type WhoAmI = {
  username: string;
  root?: string;
  roots?: string[];
  libs?: string[];
};
