const _ = require('lodash');
const sendHandledRequest = require('../../../lib/sendHandledRequest');

function toggleService(req, res, next) {
    return sendHandledRequest({
        method: 'post',
        url: [req.config.api.directory, 'services', req.query.name, req.query.action],
        source: req,
        label: `${req.query.action}_${req.query.name}`,
    })
        .then(() => {
        // дополняем список сервисов в `req.context.organizations`
            const orgId = _.get(req.context, 'state.organization');
            const org = _.find(req.context.organizations, { id: Number(orgId) });
            let index;

            if (org && org.services) {
                index = _.findIndex(org.services, { slug: req.query.name });
                if (index !== -1) {
                    switch (req.query.action) {
                        case 'enable':
                            _.extend(org.services[index], {
                                ready: false,
                                enabled: true,
                            });
                            break;
                        case 'disable':
                            _.extend(org.services[index], {
                                ready: true,
                                enabled: false,
                            });
                            break;
                    }
                }
            }

            return next ? next() : req;
        })
        .catch(next);
}

module.exports = {
    toggleService,
};
