/**
 * Error Handler Middleware
 * Centralized error handling middleware for Express
 */

// Import logger utility
const logger = require('../utils/logger');
// Import response utility
const response = require('../utils/response');
// Import custom error classes
const { AppError } = require('../utils/errors');

/**
 * Global error handler middleware
 * Handles all errors in the application
 * @param {Error} err - Error object
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 * @param {Function} next - Express next middleware function
 */
const errorHandler = (err, req, res, next) => {
  // Log error with request details
  logger.error({
    message: err.message, // Error message
    stack: err.stack, // Error stack trace
    url: req.url, // Request URL
    method: req.method, // HTTP method
    ip: req.ip, // Client IP address
  });

  // Handle known operational errors (custom AppError instances)
  if (err.isOperational) {
    // Get additional error details (check both errors and items properties)
    const errorDetails = err.errors || err.items || null;
    
    // Ensure statusCode is a valid number
    const statusCode = typeof err.statusCode === 'number' ? err.statusCode : 500;
    
    // Return error response with status code from error
    return response.error(
      res,
      err.message, // Error message
      statusCode, // HTTP status code from error (ensure it's a number)
      errorDetails // Additional error details if available
    );
  }

  // Handle unknown/unexpected errors (non-operational)
  // Don't expose internal error details in production
  const message = process.env.NODE_ENV === 'production' 
    ? 'Internal Server Error' // Generic message in production
    : err.message; // Actual error message in development

  // Return generic error response
  return response.error(res, message, 500);
};

/**
 * 404 Not Found handler middleware
 * Handles requests to undefined routes
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 * @param {Function} next - Express next middleware function
 */
const notFoundHandler = (req, res, next) => {
  // Return 404 not found response
  return response.notFound(res, `Route ${req.method} ${req.url} not found`);
};

// Export error handling middlewares
module.exports = {
  errorHandler, // Global error handler
  notFoundHandler, // 404 handler
};

