const getUrl = require('../lib2/getUrl');

const SupportedServiceSlugs = [
    'alice_b2b',
    'browser',
    'calendar',
    'direct',
    'disk',
    'forms',
    'landings',
    'mail',
    'metrika',
    'staff',
    'tracker',
    'webmaster',
    'wiki',
    'yamb',
    'yandexsprav',
];

const cloudServices = new Set([
    'wiki',
    'forms',
    'tracker',
]);

module.exports = () => [
    (req, res, next) => {
        if (!SupportedServiceSlugs.includes(req.params.serviceSlug)) {
            return next('route');
        }

        next();
    },
    (req, res, next) => {
        const { serviceSlug } = req.params;

        // @see DIR-10400
        if (cloudServices.has(serviceSlug)) {
            const redirectUrl = req.config.ui.cloud.promo[serviceSlug];

            // eslint-disable-next-line no-console
            console.log('Redirect to cloud promo', {
                requestId: req.ctx.requestId,
                uid: req.blackbox && req.blackbox.uid,
                currentUrl: getUrl(req),
                redirectUrl,
                serviceSlug,
            });

            res.redirect(redirectUrl);
        } else {
            next();
        }
    },
    require('@yandex-int/express-http-uatraits')(),
    require('@yandex-int/express-yandexuid')(),
    require('../middleware2/redirect360')(),
    require('../middleware2/htmlCsp')(),
    require('../middleware2/unsupportedBrowser')(),
    require('../middleware2/tvm')(),
    require('../middleware2/blackbox')(),
    require('../middleware2/pageViewAuth')(),
    require('@yandex-int/express-secretkey')(),
    require('../middleware2/karma')(),
    require('../middleware2/accountUpgrade')(),
    require('../middleware2/orgs')(),
    require('../middleware2/orgId')(),
    require('../middleware2/orgIdCookie')(),
    require('../middleware2/orgInfo')(),
    require('../middleware2/features')(),
    require('../middleware2/withValidOrg')(),
    require('../middleware2/blackboxPatch')(),
    require('../middleware2/userInfo')(),
    require('../middleware2/services')(),
    require('../middleware2/withAvailableService')(),
    require('../middleware2/permissions')(),
    require('../middleware2/orgSettings')(),
    require('../middleware2/userSettings')(),
    require('../middleware2/withEnabledService')(),
    require('../middleware2/legacyAdapter')(),
    require('../layouts/services'),
];
