export const errorHandler = (err, req, res, _next) => {
  if (process.env.NODE_ENV !== 'test') {
    console.error(`[${new Date().toISOString()}] ${req.method} ${req.originalUrl} -> ${err.stack || err.message}`);
  }

  if (err.code === 'LIMIT_FILE_SIZE') {
    return res.status(400).json({
      success: false,
      message: 'File too large. Maximum size is 5MB.',
      errors: ['File size exceeds the 5MB limit.'],
    });
  }

  if (err.message === 'Only JPG, JPEG, PNG, and WEBP images are allowed') {
    return res.status(400).json({
      success: false,
      message: err.message,
      errors: [err.message],
    });
  }

  let message = err.message || 'Internal Server Error';
  let errors = [];

  if (err.name === 'ValidationError') {
    message = 'Validation Error';
    errors = Object.values(err.errors).map((e) => e.message);
    return res.status(400).json({ success: false, message, errors });
  }

  if (err.code === 11000) {
    const field = Object.keys(err.keyValue)[0];
    message = `Duplicate value for ${field}`;
    return res.status(400).json({ success: false, message, errors: [message] });
  }

  if (err.name === 'CastError') {
    message = `Invalid ${err.path}: ${err.value}`;
    return res.status(400).json({ success: false, message, errors: [message] });
  }

  if (err.name === 'JsonWebTokenError') {
    message = 'Invalid token';
    return res.status(401).json({ success: false, message, errors: [message] });
  }

  if (err.name === 'TokenExpiredError') {
    message = 'Token expired';
    return res.status(401).json({ success: false, message, errors: [message] });
  }

  const statusCode = err.statusCode || 500;
  const response = { success: false, message, errors: errors.length ? errors : [message] };

  if (process.env.NODE_ENV === 'development') {
    response.stack = err.stack;
  }

  res.status(statusCode).json(response);
};
