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

module.exports = tvmConfig => (req, res, next) => {
    let { proxyUrl } = tvmConfig;
    let proxyOptions = {
        headers: {
            Cookie: req.get('Cookie'),
        },
    };

    fetch(patchFetchUrl(req, proxyUrl).href, proxyOptions)
        .then(res => res.ok ? res.json() : { error: res.statusText })
        .then(data => {
            req.tvm = { ...data, proxied: true };

            next();
        });
};
