const errorHandler = (err, req, res, next) => {
  if (res.headersSent) {
    return next(err);
  }

  let error = { ...err };
  error.message = err.message;

  // Log error for debugging
  console.error('Error:', err);

  // Sequelize validation error
  if (err.name === 'SequelizeValidationError') {
    const message = err.errors.map(e => e.message).join(', ');
    error = {
      message,
      statusCode: 400
    };
  }

  // Sequelize unique constraint error
  if (err.name === 'SequelizeUniqueConstraintError') {
    const message = 'Duplicate entry. This record already exists.';
    error = {
      message,
      statusCode: 409
    };
  }

  // Sequelize foreign key constraint error
  if (err.name === 'SequelizeForeignKeyConstraintError') {
    const message = 'Referenced record does not exist.';
    error = {
      message,
      statusCode: 400
    };
  }

  // Sequelize database error
  if (err.name === 'SequelizeDatabaseError') {
    // Try to extract more specific error information
    let message = 'Database operation failed.';
    if (err.original) {
      // MySQL errors often have useful messages in original.sqlMessage
      if (err.original.sqlMessage) {
        message = err.original.sqlMessage;
      } else if (err.original.message) {
        message = err.original.message;
      }
    } else if (err.message && err.message !== 'Database operation failed.') {
      message = err.message;
    }
    error = {
      message,
      statusCode: 500
    };
  }

  res.status(error.statusCode || 500).json({
    success: false,
    message: error.message || 'Server Error',
    ...(process.env.NODE_ENV === 'development' && { stack: err.stack })
  });
};

const notFound = (req, res, next) => {
  if (res.headersSent) {
    return next();
  }
  const error = new Error(`Not Found - ${req.originalUrl}`);
  error.statusCode = 404;
  next(error);
};

module.exports = {
  errorHandler,
  notFound
};

