const getUrl = require('../lib2/getUrl');

const ValidStatuses = ['VALID', 'NEED_RESET'];

module.exports = () => (req, res, next) => {
    let { blackbox } = req;
    let status = blackbox && blackbox.status;

    if (!ValidStatuses.includes(status)) {
        let { requestId } = req.ctx;

        // eslint-disable-next-line no-console
        console.log('Unauthorized', {
            requestId,
            status,
            uid: blackbox && blackbox.uid,
            currentUrl: getUrl(req),
        });

        res.set('x-request-id', requestId);

        if (!req.accepts('json')) {
            return res.status(401).send(status);
        }

        res.status(401).json({
            code: status,
        });
    }

    next();
};
