const { validationResult } = require('express-validator');

/**
 * Validation check middleware — call after express-validator chains.
 * Returns 422 with field-level errors if validation fails.
 */
function validateRequest(req, res, next) {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(422).json({
      error: 'Validation failed',
      details: errors.array().map((e) => ({ field: e.path, message: e.msg })),
    });
  }
  next();
}

/**
 * Global Express error handler — must be registered last.
 */
function globalErrorHandler(err, req, res, next) {
  console.error(err);

  // Prisma known errors
  if (err.code === 'P2025') {
    return res.status(404).json({ error: 'Record not found' });
  }
  if (err.code === 'P2003') {
    return res.status(400).json({ error: 'Foreign key constraint failed — referenced record does not exist' });
  }
  if (err.code === 'P2002') {
    return res.status(409).json({ error: 'A record with these unique fields already exists' });
  }

  const status = err.status || 500;
  const message = process.env.NODE_ENV === 'production' ? 'Internal server error' : err.message;
  res.status(status).json({ error: message });
}

module.exports = { validateRequest, globalErrorHandler };
