// временный адаптер, воссоздающий данные в том виде,
// в каком они выходили из легаси-миддлвар
const legacyAuthAdapter = require('./legacyAuthAdapter');
const legacyDirectoryHeaders = require('./legacyDirectoryHeaders');
const getLanguage = require('../lib2/getLanguage');

module.exports = () => [
    (req, res, next) => {
        if (!req.context) {
            req.context = {};
        }

        next();
    },
    legacyDirectoryHeaders(),
    legacyAuthAdapter(), // blackbox + tvm
    (req, res, next) => {
        let { secretkey } = req;
        let {
            orgs,
            orgId,
            user,
            features,
            services,
            permissions,
            orgSettings,
            userSettings,
            headerSettings,
            admin,
            adminGroupId,
            invite,
            requestId,
            showCaptcha,
        } = req.ctx;

        req.context = {
            ...req.context,
            organizations: orgs,
            currentUser: user,
            features,
            services,
            permissions,
            organization_settings: orgSettings,
            user_settings: userSettings,
            header_settings: headerSettings,
            sk: secretkey,
            requestId,
            isCaptchaRequired: showCaptcha,
            users: {},
            groups: {},
        };

        req.context.headers = {
            'Accept-Language': getLanguage(req),
            ...req.context.headers,
            ...req.context.auth,
            'x-request-id': requestId,
        };

        if (orgId) {
            req.context.state.organization = orgId;
            req.context.headers['x-org-id'] = orgId;
        }

        if (user) {
            req.context.users[user.id] = user;
        }

        if (admin && admin.object && adminGroupId) {
            req.context.groups[adminGroupId] = {
                members: [{ type: 'user', id: String(admin.object.id) }],
            };
            req.context.users[admin.object.id] = admin.object;
        }

        if (invite) {
            req.context.invites = {
                [invite.code]: invite,
            };
        }

        next();
    },
];
