import { z } from "zod";

/**
 * Parse a JSON request body, turning a malformed or empty body into a
 * `ZodError` rather than letting the raw `SyntaxError` from `request.json()`
 * fall through a route's generic `catch` and become an HTTP 500.
 *
 * Why a `ZodError` specifically: every body-parsing route already maps
 * `instanceof z.ZodError` to a 400. Throwing one here means a malformed body
 * returns 400 across all of them with no per-route catch changes — the call
 * site swaps `request.json()` for `readJsonBody(request)` and nothing else
 * moves. (It is a genuine `z.ZodError`, so the `instanceof` checks hold.)
 */
export async function readJsonBody(request: Request): Promise<unknown> {
  try {
    return await request.json();
  } catch {
    throw new z.ZodError([
      {
        code: z.ZodIssueCode.custom,
        path: [],
        message: "Request body must be valid JSON",
      },
    ]);
  }
}
