/**
 * Shared helpers for `/api/fetch-proxy` clients.
 *
 * The local CLI / Swift server tags its own infrastructure errors with the
 * `X-Proxy-Error: 1` response header. Without that marker, an upstream's
 * legitimate 4xx/5xx response (e.g. Google's `400 invalid_client`) was
 * historically conflated with proxy failure and turned into a thrown
 * `Error`, which the just-bash curl shim ultimately stringified through
 * `String(error)` — yielding `curl: (1) [object Object]` whenever the
 * upstream JSON body shaped its `error` field as an object.
 *
 * Use these helpers so all three SecureFetch callsites (`wasm-shell.ts`,
 * `git-http.ts`, `tray-leader.ts`) behave the same way.
 */

/**
 * True iff the response was generated by the proxy itself (missing
 * `X-Target-URL`, blocked secret domain, upstream fetch threw, etc.).
 * False for any response forwarded from upstream — even when its status
 * is 4xx or 5xx.
 */
export function isProxyError(resp: Response): boolean {
  return resp.headers.get('x-proxy-error') === '1';
}

/**
 * Read the proxy's JSON error body and produce a human-readable message.
 *
 * Tolerates non-JSON bodies and `error` fields that are themselves
 * objects (`{ "error": { "code": 400, "message": "…" } }`) — those
 * previously produced `[object Object]` because `new Error(obj)` coerces
 * its argument via `String(obj)`.
 */
export async function readProxyErrorMessage(resp: Response): Promise<string> {
  const fallback = `Proxy error ${resp.status}`;
  let text: string;
  try {
    text = await resp.text();
  } catch {
    return fallback;
  }
  return parseProxyErrorBody(text, fallback);
}

/** Pure helper, exposed for testability. */
export function parseProxyErrorBody(text: string, fallback: string): string {
  let parsed: unknown;
  try {
    parsed = JSON.parse(text);
  } catch {
    return fallback;
  }
  if (!parsed || typeof parsed !== 'object') return fallback;
  const e = (parsed as { error?: unknown }).error;
  if (typeof e === 'string' && e.length > 0) return e;
  if (e && typeof e === 'object') {
    const message = (e as { message?: unknown }).message;
    if (typeof message === 'string' && message.length > 0) return message;
    try {
      return JSON.stringify(e);
    } catch {
      return fallback;
    }
  }
  return fallback;
}
