/**
 * Error Handling Middleware
 */

/**
 * Handle 404 Not Found
 */
const notFound = (req, res, next) => {
  const error = new Error(`Not Found - ${req.originalUrl}`);
  res.status(404);
  next(error);
};

/**
 * Global Error Handler
 */
const errorHandler = (err, req, res, next) => {
  // Log error for debugging
  console.error("Error:", {
    message: err.message,
    stack: process.env.NODE_ENV === "development" ? err.stack : undefined,
    path: req.path,
    method: req.method,
  });

  // Determine status code
  let statusCode = res.statusCode === 200 ? 500 : res.statusCode;

  // Handle specific error types
  if (err.code === "ER_DUP_ENTRY") {
    statusCode = 409;
    err.message = "Duplicate entry. This record already exists.";
  }

  if (err.code === "ER_NO_REFERENCED_ROW_2") {
    statusCode = 400;
    err.message = "Invalid reference. Related record does not exist.";
  }

  // Send error response
  res.status(statusCode).json({
    success: false,
    message: err.message,
    stack: process.env.NODE_ENV === "development" ? err.stack : undefined,
  });
};

module.exports = {
  notFound,
  errorHandler,
};
