const _ = require('lodash');
const i18n = require('../lib/i18n');
const responseFilter = require('../lib/responseFilter');
const responseContext = require('../lib/responseContext');
const renderIndex = require('./index');
const Features = require('../constants/Features');

function filterLocaleDictionary(dictionary) {
    dictionary = _.pick(dictionary, [
        'common',
        'footer',
        'backend_errors',
        'common_options',
        'app_menu',
        'related_services',
        'onboarding',
        'invites',
    ]);

    dictionary.common = _.omit(dictionary.common, [
        'action', 'status', 'suggest_search_placeholder',
    ]);

    return dictionary;
}

module.exports = (req, res, next) => {
    const appRoot = _.get(req.config, 'app.root');

    if (!responseContext.isFeatureEnabled(req, Features.CAN_WORK_WITHOUT_OWNED_DOMAINS)) {
        return res.redirect(`${appRoot}home`);
    }

    responseFilter.preprocessMixedResponse(req.context);

    const config = req.config;

    const isInternalUser = responseContext.isInternal(req);
    const isExternalAdmin = !isInternalUser && responseContext.isAllowed(req);

    _.merge(config.app, {
        isExternalAdmin,
    });

    _.merge(req.context, {
        layoutId: 'onboarding',
        dictionary: filterLocaleDictionary(i18n.getDictionary(req)),
    });

    req.config = config;

    renderIndex(req, res, next);
};
