const getUrl = require('../lib2/getUrl');
const getService = require('../lib2/getService');
const redirectToForbidden = require('../lib2/redirectToForbidden');
const shouldShowCloudTrackerPromo = require('../lib2/shouldShowCloudTrackerPromo');

module.exports = () => (req, res, next) => {
    const { serviceSlug } = req.params;
    const service = getService(req, serviceSlug);

    if (service.available === false) {
        return redirectToForbidden(req, res, {
            logMsg: `Redirect to forbidden (services route): service ${serviceSlug} is unavailable`,
        });
    }

    // @see DIR-9977
    if (shouldShowCloudTrackerPromo(service)) {
        const redirectUrl = req.config.ui.cloud.promo.tracker;

        // eslint-disable-next-line no-console
        console.log('Redirect to Tracker cloud promo', {
            requestId: req.ctx.requestId,
            uid: req.blackbox && req.blackbox.uid,
            currentUrl: getUrl(req),
            redirectUrl,
        });

        return res.redirect(redirectUrl);
    }

    // @see DIR-10291
    if (service.slug === 'mail') {
        const { config, ctx } = req;
        const { orgId, user } = ctx;
        const { role } = user || {};
        const isAdmin = role === 'admin' || role === 'deputy_admin';

        let redirectUrl;

        if (isAdmin) {
            redirectUrl = config.mail.admin
                .replace('${org_id}', orgId || '')
                .replace('${uid}', req.blackbox.uid || '');
        } else {
            redirectUrl = config.mail.mail;
        }

        // eslint-disable-next-line no-console
        console.log('Redirect to Mail service', {
            requestId: req.ctx.requestId,
            uid: req.blackbox && req.blackbox.uid,
            currentUrl: getUrl(req),
            redirectUrl,
        });

        return res.redirect(redirectUrl);
    }

    next();
};
