const _ = require('lodash');

const getDetails = require('../util/org/getDetails');
const getSyncDetails = require('../util/org/getSyncDetails');
const getLimits = require('../util/org/getLimits');
const getAdmins = require('../util/org/getAdmins');
const getPartners = require('../util/getPartners');

const preprocessOrganization = require('../util/org/preprocess');
const layout = require('../util/layout');

const ORG_TYPES = [
    'common',
    'partner_organization',
    'education',
    'charity',
    'yandex_project',
    'cloud',
    'cloud_partner',
    'proxy_cloud_org',
    'test'
];

module.exports = (req, res, next) => {
    let orgId = req.params.org_id;

    let requests = {
        partners: getPartners(req, res)
    };

    requests.orgDetails = getDetails(req, res, { orgId })
        .then(details => {
            let requests = [
                getAdmins(req, res, orgId),
                getSyncDetails(req, res, orgId),
                getLimits(req, res, orgId)
            ];
            return Promise.all(requests)
                .then(([admins, sync, limits]) => Object.assign(
                    details || {},
                    limits && limits.limits ? limits : { limits },
                    { admins, sync }
                ));
        });

    Promise.all([ requests.orgDetails, requests.partners ])
        .then(data => {
            let org = preprocessOrganization(req, data[0]);
            let partners = _.get(data[1], 'result', []);

            if (org && org.partner_id && !org.partner)
                org.partner = _.find(partners, { id: org.partner_id });

            layout(req, res).render('org_details', { ORG_TYPES, org, partners });
        })
        .catch(next);
};
