"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateFile = exports.validateQueryAndParams = exports.validate = void 0;
const validate = (schema) => (req, res, next) => {
    const result = schema.safeParse(req.body);
    if (!result.success) {
        const firstIssue = result.error.issues[0];
        const error = new Error(firstIssue.message);
        error.statusCode = 422;
        throw error;
    }
    req.body = result.data;
    next();
};
exports.validate = validate;
const validateQueryAndParams = (schema) => (req, res, next) => {
    // Combina params e query dinamicamente
    const data = {
        ...req.params,
        ...req.query,
    };
    const result = schema.safeParse(data);
    if (!result.success) {
        const firstIssue = result.error.issues[0];
        const error = new Error(firstIssue.message);
        error.statusCode = 422;
        throw error;
    }
    // Atribui de volta aos params e query
    Object.keys(result.data).forEach((key) => {
        if (key in req.params) {
            req.params[key] = result.data[key];
        }
        else {
            req.query[key] = result.data[key];
        }
    });
    next();
};
exports.validateQueryAndParams = validateQueryAndParams;
const validateFile = (schema) => (req, res, next) => {
    try {
        // Caso seja upload single
        if (req.file) {
            const result = schema.safeParse(req.file);
            if (!result.success) {
                const error = new Error(result.error.issues[0].message);
                error.statusCode = 422;
                return next(error);
            }
        }
        // Caso seja upload multiple (array)
        if (req.files) {
            const result = schema.safeParse(req.files);
            if (!result.success) {
                const error = new Error(result.error.issues[0].message);
                error.statusCode = 422;
                return next(error);
            }
        }
        next();
    }
    catch (err) {
        next(err);
    }
};
exports.validateFile = validateFile;
