const { ApiError } = require('../utils/apiError');

const validate = (schema) => (req, res, next) => {
  try {
    const { error } = schema.validate(req.body, {
      abortEarly: false,
      stripUnknown: true
    });

    if (error) {
      const message = error.details
        .map((detail) => detail.message)
        .join(', ');
      throw new ApiError(400, message);
    }

    next();
  } catch (error) {
    next(error);
  }
};