"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateBody = void 0;
const zod_1 = require("zod");
const logger_1 = __importDefault(require("../../logger"));
const validateBody = (schema) => {
    return async (req, res, next) => {
        try {
            // Validate request body against the schema
            const validatedData = await schema.parseAsync(req.body);
            // Replace request body with validated data
            req.body = validatedData;
            next();
        }
        catch (error) {
            if (error instanceof zod_1.ZodError) {
                // Format Zod validation errors
                const formattedErrors = error.errors.map((err) => ({
                    path: err.path.join('.'),
                    message: err.message,
                }));
                logger_1.default.warn(`Request body validation failed: ${JSON.stringify({
                    errors: formattedErrors,
                    body: req.body,
                })}`);
                res.status(400).json({
                    success: false,
                    message: 'Invalid request body',
                    errors: formattedErrors,
                });
            }
            else {
                logger_1.default.error(`Unexpected error during body validation: ${error}`);
                res.status(500).json({
                    success: false,
                    message: 'Internal server error during validation',
                });
            }
        }
    };
};
exports.validateBody = validateBody;
//# sourceMappingURL=validateBody.js.map