export type ApiError = {
  message: string;
  status: number;
  details?: unknown;
};

export async function fetchJson<T>(input: RequestInfo | URL, init?: RequestInit): Promise<T> {
  const res = await fetch(input, {
    headers: { "Content-Type": "application/json", ...(init?.headers ?? {}) },
    ...init,
  });
  const text = await res.text();
  const data = text ? safeJson(text) : undefined;
  if (!res.ok) {
    const err: ApiError = {
      message: (data as any)?.error || res.statusText || "Request failed",
      status: res.status,
      details: data,
    };
    throw err;
  }
  return (data as T) ?? ({} as T);
}

function safeJson(text: string): unknown {
  try {
    return JSON.parse(text);
  } catch {
    return text;
  }
}


