const { URL } = require('url');

const getUrl = require('./getUrl');

/**
 * @param {Express.Request} req
 * @param {Express.Response} res
 * @param {Object} [params]
 * @returns {void}
 */
module.exports = function redirectToForbidden(req, res, {
    source = 'connect',
    reason = 'unavailable',
    logMsg = 'Redirect to forbidden',
    logParams,
} = {}) {
    const currentUrl = getUrl(req);
    const url = new URL('/portal/forbidden', currentUrl);

    url.searchParams.set('source', source);
    url.searchParams.set('reason', reason);
    url.searchParams.set('retpath', currentUrl);

    const redirectUrl = url.href;

    // eslint-disable-next-line no-console
    console.log(logMsg, {
        requestId: req.ctx.requestId,
        uid: req.blackbox && req.blackbox.uid,
        currentUrl,
        redirectUrl,
        ...logParams,
    });

    return res.redirect(redirectUrl);
};
