import { httpError } from "./errors.js";

export function validate(schema) {
  return (req, _res, next) => {
    const result = schema.safeParse({
      body: req.body,
      params: req.params,
      query: req.query,
    });

    if (!result.success) {
      const message = result.error.issues.map((i) => i.message).join("; ");
      return next(httpError(400, message || "Invalid request"));
    }

    req.validated = result.data;
    return next();
  };
}
