const _get = require('lodash/get');
const buildUrl = require('@connect/url-placeholders');
const getUrl = require('../lib2/getUrl');

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

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

    if (!blackbox || !ValidStatuses.includes(blackbox.status)) {
        let redirectUrl = buildUrl(_get(req.config, 'passport.session.login'), {
            retpath: currentUrl,
        });

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

        return res.redirect(redirectUrl);
    }

    if (blackbox && blackbox.status === 'NEED_RESET') {
        let redirectUrl = buildUrl(_get(req.config, 'passport.session.update'), {
            retpath: currentUrl,
        });

        // eslint-disable-next-line no-console
        console.log('Update session', {
            requestId: req.ctx.requestId,
            uid: blackbox.uid,
            status: blackbox.status,
            currentUrl,
            redirectUrl,
        });

        return res.redirect(redirectUrl);
    }

    next();
};
