import { logger } from '../logging/logger.js';

export function errorHandler(err, req, res, _next) {
  const status = err.status ?? err.statusCode ?? 500;

  logger.error({
    err: { message: err.message, stack: err.stack, code: err.code },
    method: req.method,
    url: req.url,
    userId: req.user?.id,
  }, 'request failed');

  const body = { error: status >= 500 ? 'Internal server error' : err.message };
  if (process.env.NODE_ENV !== 'production' && status >= 500) {
    body.detail = err.message;
  }
  res.status(status).json(body);
}
