const getBasicResponseHeaders = require('../lib2/getBasicResponseHeaders');
const renderError = require('../layouts/500');

module.exports = () => (err, req, res, next) => {
    if (res.headersSent) {
        return next(err);
    }

    let { name = 'Error', message, body, stack } = err;
    let { requestId } = req.ctx;

    console.error(message ? `${name}: ${message}` : 'Error', {
        message,
        body,
        stack,
        requestId,
    });

    if (req.accepts('html')) {
        req.ctx.error = err;

        // легаси-формат
        req.context = req.context || {};
        req.context.error = err;

        return renderError(req, res, next);
    }

    if (req.accepts('json')) {
        return res
            .status(500)
            .set(getBasicResponseHeaders(req))
            .json({ message, body, requestId });
    }

    return res
        .status(500)
        .set(getBasicResponseHeaders(req))
        .text(message || `Error ${requestId}`);
};
