const _ = require('lodash');
const config = require('../config');
const sanitizeHtmlContent = require('../lib/sanitizeHtmlContent');
const location = require('../lib/location');
const i18n = require('../lib/i18n');

module.exports = function (req, res, next) { // eslint-disable-line
    const dictionary = i18n.getDictionary(req);
    const refreshTime = Math.floor(30 + 60 * Math.random());
    const errorId = req.query.eid || _.get(req.context, 'headers.x-request-id');

    const content = {};

    content.description = _.get(dictionary, 'error_page.warning.description_2', '')
        .replace('{url}', `${_.get(config, 'ui.help.troubleshooting', '/')}#troubleshooting__feedback`)
        .replace('{id}', _.escape(errorId));

    content.timer = _.get(dictionary, 'error_page.warning.timer_2', '')
        .replace('{time}', refreshTime);

    req.context = req.context || {};

    let error = req.context.error;

    res.status(200).render('500', {
        debug: !config.app.isProd,
        rum: require('../rum')(req, 'error'),
        i18n: _.pick(dictionary, ['error_page']),
        locale: i18n.getLocale(req),
        retpath: location.getSafeRedirectUrl(req.query.retpath),
        refreshTime,
        description: content.description,
        timer: content.timer,
        nonce: req.nonce,
        staticPrefix: config.app.assets,
        error: sanitizeHtmlContent(error.stack || JSON.stringify(error)),
    });
};
