// @see DIR-7060
const { URL } = require('url');
const getUrl = require('../lib2/getUrl');
const getOrgIds = require('../lib2/getOrgIds');
const setYCookie = require('../lib2/setYCookie');

function toForbidden(req, res, reason) {
    let currentUrl = getUrl(req);
    let url = new URL(req.query.fallback_url || '/portal/forbidden', currentUrl);

    url.searchParams.set('origin', 'context');
    url.searchParams.set('retpath', req.query.retpath || '');
    url.searchParams.set('reason', reason || '');

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

    res.redirect(url.href);
}

module.exports = (req, res, next) => {
    let nextOrgId = req.query.org_id;
    let orgIds = getOrgIds(req);

    if (req.query.silent === '0' || req.query.iframe === '1') {
        return next();
    }

    if (orgIds.length === 0) {
        return toForbidden(req, res, 'no_orgs');
    }

    if (!orgIds.includes(nextOrgId)) {
        // @see DIR-9490
        if (req.query.autocontext === '0') {
            return next();
        }

        nextOrgId = orgIds[0];
    }

    // eslint-disable-next-line no-console
    console.log('Switch context', {
        requestId: req.ctx.requestId,
        uid: req.blackbox && req.blackbox.uid,
        query: req.query,
        nextOrgId,
        orgIds,
    });

    setYCookie(req, res, {
        org_id: nextOrgId,
        sk: req.query.sk,
        retpath: req.query.retpath,
    });
};
