const _ = require('lodash');
const sendHandledRequest = require('../../lib/sendHandledRequest');

const REQUEST_FIELDS = [
    'comment',
    'created_at',
    'service_slug',
    'department', 'department.name', 'department.members_count',
    'group', 'group.name', 'group.members_count',
    'author', 'author.name', 'author.position',
    'user', 'user.name', 'user.position',
];

function read(req, res, next) {
    return sendHandledRequest({
        method: 'get',
        url: [
            req.config.api.directory, 'v8', 'subscription',
            'services', 'tracker', 'licenses', 'request',
        ],
        query: {
            fields: REQUEST_FIELDS.join(','),
            per_page: 100, // Todo: уменьшить размер страници и перейти на инфинит скролл
        },
        source: req,
        label: 'read_license_requests',
    })
        .then(response => {
            _.set(req.context, 'licenses.requests.tracker', response.result);

            return next ? next() : req;
        });
}

function add(req, res, next) {
    return sendHandledRequest({
        method: 'post',
        url: [
            req.config.api.directory, 'v8', 'subscription',
            'services', 'tracker', 'licenses', 'request',
        ],
        source: req,
        label: 'add_license_requests',
    })
        .then(() => next ? next() : req);
}

function deny(req, res, next) {
    return sendHandledRequest({
        method: 'post',
        url: [
            req.config.api.directory, 'v8', 'subscription',
            'services', 'tracker', 'licenses', 'request', 'deny',
        ],
        source: req,
        label: 'deny_license_requests',
    })
        .then(() => read(req, res, next));
}

function confirm(req, res, next) {
    return sendHandledRequest({
        method: 'post',
        url: [
            req.config.api.directory, 'v8', 'subscription',
            'services', 'tracker', 'licenses', 'request', 'confirm',
        ],
        source: req,
        label: 'confirm_license_requests',
    })
        .then(() => read(req, res, next));
}

module.exports = {
    read,
    add,
    deny,
    confirm,
};
