const _ = require('lodash');
const user = require('./user');
const permissions = require('./permissions');
const extendedDepartment = require('./extendedDepartment');

function read(req, res, next) {
    const originalQuery = _.clone(req.query);
    const requests = [];

    const userRequest = user.read(req);

    requests.push(userRequest);

    if (originalQuery.extension === 'deep') {
        const departmentRequest = userRequest
            .then(nextReq => {
                const contextUser = _.find(nextReq.context.users, {
                    id: Number(originalQuery.id),
                });

                req.query = {
                    id: _.get(contextUser, 'department.id'),
                    extension: originalQuery.extension,
                };

                return extendedDepartment.read(req);
            });

        requests.push(departmentRequest);
    }

    if (originalQuery.extension) {
        req.query = {
            id: originalQuery.id,
            type: 'user',
        };
        const permissionsRequest = permissions.read(req);

        requests.push(permissionsRequest);
    }

    return Promise.all(requests)
        .then(nextReq => next ? next() : nextReq)
        .catch(next);
}

module.exports = _.extend({}, user, { read });
