const getUser = require('../lib2/getUser');
const isInternalAccount = require('../lib2/isInternalAccount');
const directory = require('../api2/directory');

const UserFields = [
    'role',
    'nickname',
    'name',
    'contacts',
    'timezone',
];

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

    if (!isInternalAccount(user)) {
        return next();
    }

    directory(req)
        .send('GET', `/v11/users/${user.id}/`, {
            query: {
                fields: UserFields.join(','),
            },
        })
        .then(res => res.json())
        .then(data => {
            req.ctx.user = data;

            next();
        })
        .catch(() => {
            next();
        });
};
