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

module.exports = (req, res, next) => {
    getDetails(req, res, { orgId: req.params.org_id, allowCache: true })
        .then(details => {
            return getServices(req, res)
                .then(services => {
                    return Promise.all(
                        Object.entries(services || {}).map(([ slug, service ]) => {
                            if (service.responsible_id) {
                                return getUserDetails(req, res, service.responsible_id)
                                    .then(responsible => Object.assign(service, { responsible }));
                            }

                            return service;
                        })
                    ).then(() => Object.assign(details, { services }));
                });
        })
        .then(data => {
            layout(req, res).render(
                data.code === 'not_found' ? 'org_details' : 'org_services',
                { org: preprocessOrganization(req, data) }
            );
        })
        .catch(next);
};
