const _get = require('lodash/get');
const ycookie = require('@yandex-int/y-cookie');

module.exports = () => (req, res, next) => {
    let { orgs } = req.ctx;

    if (!orgs || orgs.length === 0) {
        return next();
    }

    const ycookieOrgId = _get(ycookie.parse(req.cookies.yp), 'org_id.value');
    let orgId = req.get('x-org-id') || ycookieOrgId;

    if (!orgId || !orgs.find(({ id }) => String(id) === orgId)) {
        orgId = String(orgs[0].id);
    }

    // eslint-disable-next-line no-console
    console.log('Define org id', {
        requestId: req.ctx.requestId,
        uid: req.blackbox && req.blackbox.uid,
        'x-org-id': req.get('x-org-id'),
        orgId,
        ycookieOrgId,
        ycookieValue: req.cookies.yp,
        ycookieParsed: ycookie.parse(req.cookies.yp),
    });

    req.ctx.orgId = orgId;

    next();
};
