/**
 * Отдаёт главную страницу
 */

const _ = require('lodash');
const ycookie = require('@yandex-int/y-cookie');
const i18n = require('../lib/i18n');
const responseFilter = require('../lib/responseFilter');
const responseContext = require('../lib/responseContext');
const setYCookie = require('../lib2/setYCookie');
const sanitizeHtmlContent = require('../lib/sanitizeHtmlContent');
const getRequiredPolyfills = require('../lib2/getRequiredPolyfills');

const PUBLIC_CONFIG_ENTRIES = require('../config/public');
const PAGE_TITLE_KEY = {
    forbidden: 'forbidden_page.access_denied',
};

const MainConnectLayouts = [
    'home', 'services', 'index', 'profile', 'onboarding',
];

// eslint-disable-next-line complexity
module.exports = (req, res, next) => {
    let config = req.config;
    let { env, version } = config.app;

    const isDev = env === 'development';
    const isUITest = env === 'ui-test';

    let layoutId = req.context.layoutId || 'index';
    let canUseConnect = _.get(req.context, 'permissions.global', []).includes('use_connect') || isUITest;

    if (
        (layoutId === 'index' && (
            req.path === '/portal/setup' ||
            req.path.startsWith('/portal/staff') || // DIR-10005
            req.path.startsWith('/portal/restore') // PSBTBSUP-879
        )) ||
        (layoutId === 'services' && (
            req.params.serviceSlug === 'webmaster' // DIR-10116
        ))
    ) {
        canUseConnect = true;
    }

    if (MainConnectLayouts.includes(layoutId) && !canUseConnect) {
        return res.redirect('/portal/forbidden?reason=cannot_use_connect');
    }

    let currentOrgId = _.get(req.context, 'headers.x-org-id');
    let ycookieOrgId = _.get(ycookie.parse(req.cookies.yp), 'org_id.value');
    // @see DIR-9490
    let isAutoContextDisabled = req.query.autocontext === '0';

    // @see DIR-8938
    if (currentOrgId && currentOrgId !== ycookieOrgId && !isAutoContextDisabled && !isUITest) {
        let retpath;

        if (layoutId === 'forbidden' && req.query.reason === 'unavailable') {
            retpath = req.query.retpath;
        }

        return setYCookie(req, res, {
            org_id: currentOrgId,
            sk: req.context.sk,
            retpath: retpath || responseContext.getUrl(req, req.originalUrl),
        });
    }

    const dictionary = req.context.dictionary || i18n.getDictionary(req);
    const locale = i18n.getLocale(req);

    // использует req.context.headers
    const rumData = require('../rum')(req);

    // среди прочего отсечёт req.context.headers
    responseFilter.preprocessMixedResponse(req.context, {
        removePrivateKeys: true,
    });

    const data = {
        initial: req.context,
        config: _.pick(config, PUBLIC_CONFIG_ENTRIES),
        i18n: dictionary,
        rum: _.pick(rumData, ['service_id', 'dictionary', 'debug']),
    };

    // Устанавливаем язык пользователя здесь, потому что если делать это в конфиге,
    // то получим циклический require
    _.set(data, 'config.app.locale', locale);

    const usesFreshCode = ['home', 'services', 'profile', 'context'].includes(layoutId);
    const requiresBasicPolyfills = getRequiredPolyfills(req) !== null || isUITest;

    if (isDev) {
        version = `dev-${Math.floor(1e6 * Math.random())}`;
    }

    // eslint-disable-next-line no-console
    console.log('Layout rendered', {
        layoutId,
        requestId: req.ctx.requestId,
        uid: req.blackbox && req.blackbox.uid,
        orgId: req.ctx.orgId,
        nonce: req.nonce,
        usesFreshCode,
        requiresBasicPolyfills,
        version,
        locale,
    });

    try {
        res.render('index', {
            layoutId,
            metrika: {
                ids: {
                    portal: _.get(config, ['metrika', req.path === '/portal/setup' ? 'setup' : 'default']),
                    general: _.get(config, 'metrika.general'),
                },
                userParams: sanitizeHtmlContent({
                    UserID: _.get(data, 'initial.state.session'),
                    OrgID: _.get(data, 'initial.state.organization'),
                    YandexUID: req.cookies.yandexuid,
                }),
                nonce: req.nonce,
            },
            usesFreshCode,
            requiresBasicPolyfills,
            hmrEnabled: process.env.HOT_RELOAD,
            rum: rumData,
            data: sanitizeHtmlContent(data),
            title: _.get(dictionary, PAGE_TITLE_KEY[layoutId] || 'common.full_main_title', 'Yandex.Connect'),
            token: req.csrfToken && req.csrfToken(),
            isDev,
            isUITest,
            version,
            staticPrefix: config.app.assets,
            nonce: req.nonce,
            lang: locale,
            requiresMomentLocale: locale !== 'en',
        });
    } catch (e) {
        next(e);
    }
};
