import type { NextFunction, Request, Response } from "express";
import type { ZodSchema } from "zod";
import { sendError } from "../utils/apiResponse.js";

const validate = (source: "body" | "query" | "params", schema: ZodSchema) => {
  return (req: Request, res: Response, next: NextFunction) => {
    const result = schema.safeParse(req[source]);

    if (!result.success) {
      return sendError(
        res,
        400,
        "VALIDATION_ERROR",
        `Invalid request ${source}.`,
        result.error.flatten(),
      );
    }

    if (source === "body") req.validatedBody = result.data;
    if (source === "query") req.validatedQuery = result.data;
    if (source === "params") req.validatedParams = result.data;

    next();
  };
};

export const validateBody = (schema: ZodSchema) => validate("body", schema);
export const validateQuery = (schema: ZodSchema) => validate("query", schema);
export const validateParams = (schema: ZodSchema) => validate("params", schema);
