const fetch = require('../lib2/fetch');
const setQuery = require('../lib2/setQuery');
const patchFetchUrl = require('../lib2/patchFetchUrl');
const getEnv = require('../lib2/getEnv');

const SuggestProxyEnvs = [
    'development',
    'ui-test',
];

module.exports = () => (req, res, next) => {
    if (!SuggestProxyEnvs.includes(getEnv(req))) {
        next();
    }

    let url = setQuery(req.config.api.suggest, req.query);

    return fetch(patchFetchUrl(req, url).href, {
        headers: {
            Cookie: req.get('Cookie'),
        },
    }).then(({ body }) => body.pipe(res));
};
