const _get = require('lodash/get');
const ycookie = require('@yandex-int/y-cookie');
const setYCookie = require('../lib2/setYCookie');
const getUrl = require('../lib2/getUrl');
const getEnv = require('../lib2/getEnv');

// @see DIR-8938
module.exports = getRetpath => (req, res, next) => {
    // @see DIR-9490
    if (req.query.autocontext === '0' || getEnv(req) === 'ui-test') {
        return next();
    }

    let { orgId } = req.ctx;
    let ycookieOrgId = _get(ycookie.parse(req.cookies.yp), 'org_id.value');

    if (orgId && orgId !== ycookieOrgId && req.secretkey) {
        // eslint-disable-next-line no-console
        console.log('Y-cookie mismatch', {
            requestId: req.ctx.requestId,
            uid: req.blackbox && req.blackbox.uid,
            orgId,
            ycookieOrgId,
            ycookieValue: req.cookies.yp,
            ycookieParsed: ycookie.parse(req.cookies.yp),
        });

        return setYCookie(req, res, {
            org_id: orgId,
            sk: req.secretkey,
            retpath: getRetpath ? getRetpath(req) : getUrl(req),
        });
    }

    next();
};
