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

// для /portal/setup
// уводим внешних пользователей с дорегистрации организации
module.exports = () => (req, res, next) => {
    let user = getUser(req, 'raw');
    let currentUrl = getUrl(req);
    let internal = isInternalAccount(user);

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

    if (!internal) {
        let redirectUrl = new URL(req.query.retpath || '/', currentUrl).href;

        // eslint-disable-next-line no-console
        console.log('Setup: external user', {
            ...logProps,
            redirectUrl,
        });

        return res.redirect(redirectUrl);
    }

    next();
};
