// import { inspect } from 'util';
// import _ from 'lodash/fp';
import accepts from 'accepts';

import { homeLocation } from '../../../config/env';

import { unwrapHandledError } from '../utils/create-handled-error.js';

const isDev = process.env.FREECODECAMP_NODE_ENV !== 'production';

export default function prodErrorHandler() {
  // error handling in production.
  // eslint-disable-next-line no-unused-vars
  return function(err, req, res, next) {
    const handled = unwrapHandledError(err);
    // respect handled error status
    let status = handled.status || err.status || res.statusCode;
    if (!handled.status && status < 400) {
      status = 500;
    }
    res.status(status);

    // parse res type
    const accept = accepts(req);
    const type = accept.type('html', 'json', 'text');

    const redirectTo = handled.redirectTo || `${homeLocation}/`;
    const message =
      handled.message ||
      'Oops! Something went wrong. Please try again in a moment.';

    if (isDev) {
      console.error(err);
    }

    if (type === 'html') {
      if (typeof req.flash === 'function') {
        req.flash(handled.type || 'danger', message);
      }
      return res.redirectWithFlash(redirectTo);
      // json
    } else if (type === 'json') {
      res.setHeader('Content-Type', 'application/json');
      return res.send({
        type: handled.type || 'errors',
        message
      });
      // plain text
    } else {
      res.setHeader('Content-Type', 'text/plain');
      return res.send(message);
    }
  };
}

@@ -215,16 +215,330 @@
 r.js';%0A%0A
+const errTemplate = (error, req) =%3E %7B%0A  const %7B message, stack %7D = error;%0A  return %60%0AError: $%7Bmessage%7D%0AIs authenticated user: $%7B!!req.user%7D%0AHeaders: $%7BJSON.stringify(req.headers, null, 2)%7D%0AOriginal request: $%7Breq.originalMethod%7D $%7Breq.originalUrl%7D%0AStack: $%7Bstack%7D%0A%0A// raw%0A$%7BJSON.stringify(error, null, 2)%7D%0A%0A%60;%0A%7D;%0A%0A
 const is
@@ -1326,24 +1326,42 @@
 le.error(err
+Template(err, req)
 );%0A    %7D%0A%0A  

enhance dev error reports