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

const SKIP_CODES = ['service_not_licensed', 'service_is_not_enabled'];

function filterErrors(error, callback) {
    const code = _.get(error, 'body.code');
    const skip = SKIP_CODES.indexOf(code) !== -1;

    if (!skip) {
        throw error;
    } else if (callback) {
        callback(code);
    }
}

function read(req, res, next) {
    let serviceSlug = req.query.service;

    return sendHandledRequest({
        method: 'get',
        // url: [ req.config.api.directory, 'subscription', 'licenses' ],
        // пока один Трекер, приводим его к общему виду будующей ручки: DIR-4047
        url: [
            req.config.api.directory, 'subscription',
            'services', serviceSlug, 'licenses',
        ],
        source: req,
        label: 'read_licenses',
    })
        .then(response => {
            _.set(req.context, `licenses.subscribers.${serviceSlug}`, response);

            return next ? next() : response;
        })
        .catch(error => {
            filterErrors(error, code => {
                _.set(req.context, `subscription.status.${serviceSlug}`, code);

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

function calculate(req, res, next) {
    let serviceSlug = req.query.service;

    req.body = _.get(req.body, `subscribers.${serviceSlug}`, req.body);

    return sendHandledRequest({
        method: 'post',
        // url: [ req.config.api.directory, 'subscription', 'calculate' ],
        // пока один Трекер, приводим его к общему виду будующей ручки: DIR-4047
        url: [
            req.config.api.directory, 'subscription',
            'services', serviceSlug, 'licenses', 'calculate-price',
        ],
        source: req,
        label: 'calculate_licenses',
    })
        .then(response => {
            if (response && response.user_count !== undefined) {
                // приводим к соответствию с форматом ручки `/subscription/pricing/`
                response.users_count = response.user_count;
                delete response.user_count;
            }
            _.set(req.context, 'subscription.pricing', {
                services: {
                    [serviceSlug]: _.omit(response, 'promocode'),
                },
                total: _.get(response, 'total'),
                total_with_discount: _.get(response, 'total_with_discount'),
                promocode: _.get(response, 'promocode'),
                currency: _.get(response, 'currency', 'RUB'),
            });

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

function update(req, res, next) {
    let serviceSlug = req.query.service;

    req.body = _.get(req.body, `subscribers.${serviceSlug}`);

    return sendHandledRequest({
        method: 'put',
        // url: [ req.config.api.directory, 'subscription', 'licenses' ],
        // пока один Трекер, приводим его к общему виду будующей ручки: DIR-4047
        url: [
            req.config.api.directory, 'subscription',
            'services', serviceSlug, 'licenses',
        ],
        source: req,
        label: 'update_licenses',
    })
        .then(() => Promise.all([
            read(req),
            calculate(req),
        ]))
        .then(() => next ? next() : req)
        .catch(next);
}

function getPreview(req, res, next) {
    const originalQuery = _.clone(req.query);

    req.query = {
        fields: 'name,nickname',
        service: 'tracker.license_issued',
        per_page: 10,
    };

    return user.readList(req)
        .then(response => {
            _.set(req.context, 'licenses.preview.tracker', _.get(response, 'result'));
            req.query = originalQuery;

            return next ? next() : response;
        })
        .catch(next);
}

module.exports = {
    read, update, calculate, getPreview,
};
