export async function safeFetch(input: RequestInfo, init?: RequestInit): Promise<Response> {
  try {
    return await fetch(input, init);
  } catch (err: any) {
    const msg = err?.message ?? String(err);
    const code = err?.code ?? undefined;
    const url = typeof input === "string" ? input : (input as Request).url;
    console.debug("[safeFetch] network error", { url, code, msg });

    // Treat aborted/terminated and connection errors as soft failures
    if (
      err?.name === "AbortError" ||
      (typeof msg === "string" && (msg.includes("terminated") || msg.includes("fetch failed"))) ||
      code === "ECONNREFUSED" ||
      code === "ECONNRESET"
    ) {
      return new Response(JSON.stringify({ message: "upstream-unreachable", details: msg }), {
        status: 502,
        headers: { "content-type": "application/json" },
      });
    }

    throw err;
  }
}
