const { URL } = require('url');
const getService = require('../lib2/getService');
const getUrl = require('../lib2/getUrl');

const Subservice = {
    staff: /^\/portal\/staff(\/.*)?$/,
    dashboard: /^\/portal\/home\/?$/,
};

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

    for (let [serviceSlug, pathPattern] of Object.entries(Subservice)) {
        if (pathPattern.test(req.path) && getService(req, serviceSlug).enabled === false) {
            let url = new URL('/portal/forbidden', currentUrl);

            url.searchParams.set('source', serviceSlug);
            url.searchParams.set('reason', 'deactivated');
            url.searchParams.set('retpath', currentUrl);

            let redirectUrl = url.href;

            // eslint-disable-next-line no-console
            console.log('Access denied: service inactive', {
                requestId: req.ctx.requestId,
                uid: req.blackbox && req.blackbox.uid,
                serviceSlug,
                currentUrl,
                redirectUrl,
            });

            return res.redirect(redirectUrl);
        }
    }

    next();
};
