const _get = require('lodash/get');
const buildUrl = require('@connect/url-placeholders');
const getUser = require('../lib2/getUser');
const getUrl = require('../lib2/getUrl');
const isLiteAccount = require('../lib2/isLiteAccount');
const isSocialAccount = require('../lib2/isSocialAccount');

module.exports = () => (req, res, next) => {
    let user = getUser(req, 'raw');

    // https://wiki.yandex-team.ru/connect/support/socialnye-akkaunty-i-lajjt-akkaunty/
    let lite = isLiteAccount(user);
    let social = isSocialAccount(user);

    if (lite || social) {
        let url = buildUrl(_get(req.config, 'passport.session.upgradeUser'), {
            retpath: getUrl(req),
            tld: _get(req.config, 'app.tld', 'ru'),
        });

        // eslint-disable-next-line no-console
        console.log('Upgrade account', {
            requestId: req.ctx.requestId,
            uid: user.id,
            lite,
            social,
            url,
        });

        return res.redirect(url);
    }

    next();
};
