const { URL } = require('url');
const getUrl = require('./getUrl');
const fetch = require('./fetch');

// @see https://wiki.yandex-team.ru/cookies/y/
function fetchYCookie(req, params) {
    let url = new URL('/portal/set/any/', req.config.api.ya);

    for (let [key, value] of Object.entries(params)) {
        if (key !== 'retpath') {
            url.searchParams.set(key, value);
        }
    }

    url.searchParams.set('empty', 1);

    // eslint-disable-next-line no-console
    console.log('Fetch y-cookie', {
        requestId: req.ctx.requestId,
        uid: req.blackbox && req.blackbox.uid,
        fetchUrl: url.href,
        currentUrl: getUrl(req),
    });

    return fetch(url.href, {
        headers: {
            Cookie: req.get('Cookie'),
        },
    })
        .then(response => ({
            ok: response.ok,
            cookie: response.headers.get('set-cookie'),
        }));
}

module.exports = fetchYCookie;
