import { NextResponse } from "next/server";
import { z } from "zod";
import { HttpError } from "@/lib/guard";

/** Parse + validate a JSON request body, throwing 400 on failure. */
export async function parseBody<T>(req: Request, schema: z.ZodType<T>): Promise<T> {
  let json: unknown;
  try {
    json = await req.json();
  } catch {
    throw new HttpError(400, "Invalid JSON body");
  }
  const result = schema.safeParse(json);
  if (!result.success) {
    const msg = result.error.issues
      .map((i) => `${i.path.join(".") || "_"}: ${i.message}`)
      .join("; ");
    throw new HttpError(400, msg);
  }
  return result.data;
}

export function ok(data: unknown, status = 200) {
  return NextResponse.json(data, { status });
}
