import { ZodSchema, ZodError } from "zod";
import { ValidationError } from "@/lib/api/errors";

export function validateQuery<T>(req: Request, schema: ZodSchema<T>): T {
  const params = Object.fromEntries(new URL(req.url).searchParams.entries());
  try {
    return schema.parse(params);
  } catch (err) {
    if (err instanceof ZodError) {
      throw new ValidationError("Invalid query parameters", {
        code: "VALIDATION_ERROR",
        fieldErrors: err.flatten().fieldErrors,
      });
    }
    throw err;
  }
}

export async function validateBody<T>(req: Request, schema: ZodSchema<T>): Promise<T> {
  let body: unknown;
  try {
    body = await req.json();
  } catch {
    throw new ValidationError("Request body must be valid JSON", {
      code: "INVALID_JSON",
    });
  }
  try {
    return schema.parse(body);
  } catch (err) {
    if (err instanceof ZodError) {
      throw new ValidationError("Invalid request body", {
        code: "VALIDATION_ERROR",
        fieldErrors: err.flatten().fieldErrors,
      });
    }
    throw err;
  }
}
