const { URL } = require('url');
const buildUrl = require('@connect/url-placeholders');
const getUrl = require('../lib2/getUrl');

module.exports = (url, sParams) => (req, res) => {
    let urlParams = {
        tld: (req.config.app && req.config.app.tld) || 'ru',
        ...req.params,
    };

    let currentUrl = getUrl(req);
    let redirectUrl = new URL(buildUrl(url, urlParams), currentUrl);

    for (let [k, v] of Object.entries(sParams || req.query)) {
        redirectUrl.searchParams.set(k, v);
    }

    // eslint-disable-next-line no-console
    console.log(`Redirect from ${req.path} to ${redirectUrl.origin}${redirectUrl.pathname}`, {
        requestId: req.ctx.requestId,
        redirectUrl: redirectUrl.href,
        currentUrl,
    });

    res.redirect(redirectUrl.href);
};
