const { URL } = require('url');
const _ = require('lodash');
const i18n = require('../lib/i18n');
const getUrl = require('../lib2/getUrl');
const responseFilter = require('../lib/responseFilter');
const responseContext = require('../lib/responseContext');
const renderIndex = require('./index');

function getServiceSlug(req, retpath) {
    let services = _.get(req.config, 'ui.relatedServices', {});
    let retpathUrl;

    try {
        retpathUrl = new URL(retpath);
    } catch (e) {
        return;
    }

    for (let [serviceSlug, url] of Object.entries(services)) {
        try {
            let { hostname, pathname } = new URL(url);
            let isSubdomain = hostname.split('.').length > 2; // 'service.yandex.ru'

            if (hostname === retpathUrl.hostname && (isSubdomain || pathname === retpathUrl.pathname)) {
                return serviceSlug;
            }
        } catch (e) {
            // ignore
        }
    }
}

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

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

    return dictionary;
}

module.exports = (req, res, next) => {
    if (req.query.reason === 'no_orgs') {
        const currentUrl = getUrl(req);
        const url = new URL('/portal/registration', currentUrl);

        url.searchParams.set('action', 'add');
        url.searchParams.set('reason', 'no_orgs');
        url.searchParams.set('source', req.query.source || getServiceSlug(req, req.query.retpath) || 'connect');

        return res.redirect(url.href);
    }

    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: 'forbidden',
        dictionary: filterLocaleDictionary(i18n.getDictionary(req)),
    });

    req.config = config;

    renderIndex(req, res, next);
};
