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

function preprocessServices(req, data) {
    const isDev = _.get(req.config, 'app.isDev');
    const relatedServices = _.get(req.config, 'ui.relatedServices');

    if (isDev && data.services && relatedServices) {
        data.services.forEach(service => {
            service.url = relatedServices[service.slug] || service.url;
        });
    }

    return data;
}

function readMenu(req, res, next) {
    return sendHandledRequest({
        method: 'get',
        url: `${req.config.api.directory}/ui/header`,
        source: req,
        query: {
            language: req.query.language || i18n.getLocale(req),
            tld: req.query.tld || req.config.app.tld,
        },
        label: 'read_header_services',
    })
        .then(response => {
            req.context.header_settings = _.extend(
                req.context.header_settings || {},
                preprocessServices(req, response)
            );

            return next ? next() : req;
        })
        .catch(() =>
        // игнорируем ошибки в этом методе API:
        // отсутствие информации о сервисах не влияет на полную работоспособность
            next ? next() : req
        );
}

function readAll(req, res, next) {
    return sendHandledRequest({
        method: 'get',
        url: `${req.config.api.directory}/services`,
        source: req,
        query: {
            language: req.query.language || i18n.getLocale(req),
            tld: req.query.tld || req.config.app.tld,
        },
        label: 'read_all_services',
    })
        .then(response => {
            req.context.services = response;

            return next ? next() : req;
        })
        .catch(() =>
        // игнорируем ошибки в этом методе
            next ? next() : req
        );
}

function update(req, res, next) {
    return sendHandledRequest({
        method: 'patch',
        url: `${req.config.api.directory}/services/${req.query.service}/`,
        source: req,
        label: 'set_service_responsible',
    })
        .then(() => resources.getResponsible(req, res, next));
}

module.exports = {
    readMenu,
    readAll,
    update,
};
