/**
 * Async handler wrapper - Eliminates try/catch boilerplate
 */
const { AppError } = require('../utilities/errors');

/**
 * Wrap async route handlers - catches errors and logs them
 */
function asyncHandler(logError, fn, context) {
  return async (req, res, next) => {
    try {
      await fn(req, res, next);
    } catch (error) {
      // Let typed errors propagate to global error handler
      if (error instanceof AppError) {
        return next(error);
      }
      
      await logError(context || req.path, error);
      
      if (!res.headersSent) {
        const { errorResponse } = require('./responses');
        const { safeErrorMessage } = require('./logging');
        errorResponse(res, 500, safeErrorMessage(error));
      }
    }
  };
}

module.exports = { asyncHandler };
