const _get = require('lodash/get');
const directory = require('../api2/directory');
const getUser = require('../lib2/getUser');
const isInternalAccount = require('../lib2/isInternalAccount');

module.exports = () => (req, res, next) => {
    if (!isInternalAccount(getUser(req, 'raw'))) {
        return next();
    }

    directory(req)
        .send('GET', '/v11/groups/', {
            query: {
                type: 'organization_admin',
                fields: 'members',
            },
        })
        .then(res => res.json())
        .then(data => {
            req.ctx.admin = _get(data, 'result[0].members[0]');
            req.ctx.adminGroupId = _get(data, 'result[0].id');

            next();
        })
        .catch(() => {
            next();
        });
};
