const directory = require('../api2/directory');

const OrgFields = [
    'id',
    'name',
    'language',
    'organization_type',
    'domains',
    'services',
    'vip',
    'admin_id',
    'country',
    'has_owned_domains',
    'subscription_plan',
    'root_departments.name',
    'can_users_change_password',
    'logo',
    'is_blocked',
    'fax',
    'email',
    'phone_number',
];

module.exports = () => (req, res, next) => {
    let { orgs, orgId } = req.ctx;

    if (!orgId) {
        return next();
    }

    directory(req)
        .send('GET', `/v11/organizations/${orgId}/`, {
            query: {
                fields: OrgFields.join(','),
            },
        })
        .then(res => {
            if (!res.ok) {
                throw res;
            }

            return res.json();
        })
        .then(data => {
            if (orgs) {
                let k = orgs.findIndex(({ id }) => String(id) === orgId);

                if (k !== -1) {
                    req.ctx.orgs[k] = data;
                }
            } else {
                req.ctx.orgs = [data];
            }

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