const get = require('lodash/get');
const hasActiveExperiment = require('../lib2/hasActiveExperiment');
const disableExperiment = require('../lib2/disableExperiment');

const EXPERIMENT_ID = 'redirect360';
const REDIRECT_URL = 'https://admin.yandex.ru?from=connect';

module.exports = () => (req, res, next) => {
    if (!hasActiveExperiment(req, EXPERIMENT_ID)) {
        next();

        return;
    }

    const logOptions = {
        requestId: req.ctx.requestId,
        uid: req.blackbox && req.blackbox.uid,
        yandexuid: req.cookies.yandexuid,
        experiment: get(req.config, ['experiment', EXPERIMENT_ID]),
        currentUrl: req.originalUrl,
        redirectUrl: REDIRECT_URL,
    };

    // eslint-disable-next-line no-console
    console.log(`Pre-selected for experiment '${EXPERIMENT_ID}'`, logOptions);

    if (req.query.noredirect !== undefined) {
        // eslint-disable-next-line no-console
        console.log(`Opting out of experiment '${EXPERIMENT_ID}'`, logOptions);

        disableExperiment(res, EXPERIMENT_ID, { maxAge: 3600000 });
        next();

        return;
    }

    // eslint-disable-next-line no-console
    console.log(`Applying experiment '${EXPERIMENT_ID}'`, logOptions);

    // redirecting to Yandex 360 for Business
    // @see DIR-10112
    res.redirect(REDIRECT_URL);
};
