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

module.exports = (req, res, next) => {
    getDetails(req, res, { orgId: req.params.org_id, allowCache: true })
        .then(details => {
            return getActions(req, res)
                .then(actions => Object.assign({}, details, { actions }));
        })
        .then(data => {
            if (data && data.actions && data.actions.result) {
                let requests = data.actions.result.map(action => {
                    return getUserDetails(req, res, action.author_id)
                        .then(userDetails => {
                            action.author = preprocessUser(req, userDetails);
                        });
                });
                return Promise.all(requests).then(() => data);
            }
            return data;
        })
        .then(data => {
            layout(req, res).render(
                data.code === 'not_found' ? 'org_details' : 'org_actions',
                { org: preprocessOrganization(req, data) }
            );
        })
        .catch(next);
};
