const { URL } = require('url');
const isInternalAccount = require('../lib2/isInternalAccount');
const getUser = require('../lib2/getUser');
const getOrg = require('../lib2/getOrg');
const getUrl = require('../lib2/getUrl');
const redirectToForbidden = require('../lib2/redirectToForbidden');

module.exports = () => (req, res, next) => {
    if (req.path.startsWith('/portal/restore')) {
        return next();
    }

    let { orgs } = req.ctx;

    let user = getUser(req, 'raw');
    let org = getOrg(req);
    let currentUrl = getUrl(req);

    let valid = Boolean(org && org.name && org.language);
    let internal = isInternalAccount(user);

    let logProps = {
        requestId: req.ctx.requestId,
        uid: user.id,
        internal,
        currentUrl,
    };

    // forbidden для внешних пользователей без организаций,
    // внешние пользователи с организациями - внешние админы
    if (!internal && (!orgs || orgs.length === 0)) {
        return redirectToForbidden(req, res, {
            reason: 'external-user',
            logMsg: 'Access denied: external user',
            logParams: {
                internal,
                orgCount: orgs ? orgs.length : null,
            },
        });
    }

    // отмечен в Паспорте как пользователь Коннекта (internal),
    // но нет валидной организации - ведём на дорегистрацию
    if (internal && !valid) {
        let redirectUrl;

        if (req.cookies.invalid_org) {
            const url = new URL('/portal/forbidden', currentUrl);

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

            redirectUrl = url.href;
        } else {
            redirectUrl = new URL('/portal/setup', currentUrl).href;
        }

        if (req.path === '/portal/setup') {
            res.cookie('invalid_org', '1', { maxAge: 30000 });
        }

        // eslint-disable-next-line no-console
        console.log('Invalid org', {
            ...logProps,
            valid,
            redirectUrl,
            invalidOrgCookie: Boolean(req.cookies.invalid_org),
        });

        return res.redirect(redirectUrl);
    }

    if (org && org.is_blocked) {
        return redirectToForbidden(req, res, {
            reason: 'blocked-org',
            logMsg: 'Redirect to forbidden: Blocked org',
        });
    }

    const { features } = req.ctx;

    if (features && features.use_cloud_proxy && features.use_cloud_proxy.enabled) {
        const { orgId } = req.ctx;
        const url = new URL('/portal/context', currentUrl);

        url.searchParams.set('silent', '0');
        url.searchParams.set('org_id', orgId);

        const redirectUrl = url.href;

        // eslint-disable-next-line no-console
        console.log('Redirect to context: cloud_org', { ...logProps, redirectUrl });

        return res.redirect(redirectUrl);
    }

    next();
};
