const { ServiceSlugMap } = require('../config/route_maps');
const getResourceHistory = require('../util/getResourceHistory');
const getUserDetails = require('../util/getUserDetails');
const preprocessPagedList = require('../util/preprocessPagedList');
const layout = require('../util/layout');

module.exports = (req, res, next) => {
    let { resource_id: id, service_slug: serviceSlug } = req.params;

    if (serviceSlug in ServiceSlugMap) {
        serviceSlug = ServiceSlugMap[serviceSlug];
    }

    getResourceHistory(req, res, { id, serviceSlug })
        .then(data => {
            if (Array.isArray(data.result)) {
                return Promise.all(
                    data.result.map(item => {
                        return getUserDetails(req, res, item.author_id)
                            .then(userData => {
                                item.author = userData;
                            });
                    })
                ).then(() => data);
            }
        })
        .then(data => {
            preprocessPagedList(req, data);

            layout(req, res).render('resource_history', {
                resource_id: id,
                service_slug: serviceSlug,
                history: data
            });
        })
        .catch(next);
};
