/*
 * Чтение полной информации о пользователе
 */

const sendHandledRequest = require('../lib/sendHandledRequest');
const responseContext = require('../lib/responseContext');

const USER_FIELDS = [
    'aliases', 'birthday', 'timezone', 'contacts', 'department',
    'email', 'gender', 'groups', 'groups.name, groups.type', 'role',
    'is_dismissed', 'is_enabled', 'name', 'nickname',
    'position',
];

function readUserData(req, res, next) {
    if (!responseContext.isInternal(req) || responseContext.isSetup(req)) {
        next();

        return;
    }

    return sendHandledRequest({
        method: 'get',
        url: [
            req.config.api.directory, 'v6', 'users',
            { value: responseContext.getSessionId(req), type: 'number' },
        ],
        source: req,
        query: {
            fields: USER_FIELDS.join(','),
        },
        timeout: 20000,
        label: 'read_current_user',
    })
        .then(userData => {
            req.context.currentUser = userData;
            next();
        })
        .catch(next);
}

module.exports = readUserData;
