const Joi = require('joi');
const { ValidationError } = require('../utils/errors');

const schemas = {
  '/api/users': {
    POST: Joi.object({
      email: Joi.string().email().required(),
      password: Joi.string().min(8).required(),
      name: Joi.string().min(2).required()
    })
  }
};

const validateRequest = (req, res, next) => {
  const schema = schemas[req.path]?.[req.method];
  if (!schema) return next();

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

  if (error) {
    const message = error.details.map(detail => detail.message).join(', ');
    return next(new ValidationError(message));
  }

  next();
};

module.exports = { validateRequest };