// @see DIR-9506, DIR-7060
const getOrgIds = require('../lib2/getOrgIds');
const fetchYCookie = require('../lib2/fetchYCookie');

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

    if (orgIds.length === 0) {
        return res.status(403).json({
            reason: 'no_orgs',
        });
    }

    if (!orgIds.includes(nextOrgId) && req.query.autocontext !== '0') {
        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,
    });

    return fetchYCookie(req, {
        org_id: nextOrgId,
        sk: req.query.sk,
    })
        .then(({ ok, cookie }) => {
            if (!cookie) {
                res.status(ok ? 422 : 400);
            } else if (req.query.autocontext !== '0') {
                res.set('set-cookie', cookie);
            }

            res.json({
                org_id: nextOrgId,
                cookie,
            });
        });
};
