const { URL } = require('url');
const fetch = require('node-fetch');
const log = require('../util/common/log');

module.exports = (req, res, next) => {
    let { method, headers, api, path, body, query } = req.body;
    let { config } = req.context;

    let url;

    if (api) {
        url = new URL(`${config.api[api]}${path || ''}`);
    } else {
        url = new URL(`${config.api.directory_admin}${req.path}`);

        if (!headers) {
            headers = req.context.headers;
        }
    }

    query = toJSON(query);

    if (query) {
        Object.entries(query).forEach(([key, value]) => {
            url.searchParams.set(key, value);
        });
    }

    if (body === '') {
        body = undefined;
    }

    return log(fetch)(url.href, { method, headers, body })
        .then(response => response.text())
        .then(content => {
            // проверяем, что content - json-объект
            try {
                JSON.parse(content);

                res.type('json').send(content);
            }
            catch(e) {
                res.type('text').send(content);
            }
        })
        .catch(next);
};

function toJSON(x) {
    try {
        return JSON.parse(x);
    }
    catch(e) {
        return {};
    }
}
