const logger = require('../utils/logger');

/**
 * Global error-handling middleware.
 * Express recognises it by its 4-parameter signature.
 */
function errorHandler(err, _req, res, _next) {
  logger.error('Unhandled error:', err);

  // MySQL duplicate entry (unique constraint)
  if (err.code === 'ER_DUP_ENTRY' || err.errno === 1062) {
    return res.status(409).json({ error: 'Duplicate entry – resource already exists.' });
  }
  // MySQL foreign-key constraint fails
  if (err.code === 'ER_NO_REFERENCED_ROW_2' || err.errno === 1452) {
    return res.status(400).json({ error: 'Referenced resource does not exist.' });
  }
  // MySQL cannot delete/update parent row
  if (err.code === 'ER_ROW_IS_REFERENCED_2' || err.errno === 1451) {
    return res.status(400).json({ error: 'Cannot delete – resource is referenced elsewhere.' });
  }
  // MySQL column cannot be null
  if (err.code === 'ER_BAD_NULL_ERROR' || err.errno === 1048) {
    return res.status(400).json({ error: `Missing required field: ${err.message}` });
  }

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

module.exports = errorHandler;
