import type { RequestHandler } from "express";
import { ZodError, type ZodSchema } from "zod";

import { ValidationError } from "../utils/app-error.js";

type SchemaMap = {
  body?: ZodSchema;
  params?: ZodSchema;
  query?: ZodSchema;
};

export const validate = (schemas: SchemaMap): RequestHandler => (request, _response, next) => {
  try {
    if (schemas.body) {
      request.body = schemas.body.parse(request.body);
    }

    if (schemas.params) {
      request.params = schemas.params.parse(request.params);
    }

    if (schemas.query) {
      request.query = schemas.query.parse(request.query) as typeof request.query;
    }

    next();
  } catch (error) {
    next(new ValidationError("Validation failed", error instanceof ZodError ? error.flatten() : error));
  }
};
