import { NextFunction, Request, Response } from "express";
import httpStatus from "http-status";
import { ZodSchema } from "zod";
import { ApiError } from "./api-error";

export const validateAndParseBody =
  (schema: ZodSchema, options?: { sanitize?: boolean }) =>
  (req: Request, res: Response, next: NextFunction) => {
    const result = schema.safeParse(req.body);
    try {
      if (!result.success) {
        // Construye errores detallados
        const validationErrors = result.error.errors.map((err) => ({
          field: err.path.join("."),
          message: err.message,
        }));

        throw new ApiError({
          status: httpStatus.BAD_REQUEST, //400
          title: "Validation Error",
          detail: "Algunos campos no cumplen con los criterios de validación.",
          type: "https://example.com/probs/validation-error",
          instance: req.originalUrl,
          errors: validationErrors,
        });
      }

      // Si pasa la validación, opcionalmente reescribe req.body
      if (options?.sanitize ?? true) {
        req.body = result.data;
      }

      next();
    } catch (error: unknown) {
      // Si ocurre un error, delega al manejador de errores global
      next(error as ApiError);
    }
  };
