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

function readState(req, res, next) {
    return sendHandledRequest({
        method: 'get',
        url: `${req.config.api.directory}/subscription/`,
        source: req,
        label: 'read_subscription_state',
    })
        .then(response => {
            _.set(req.context, 'subscription.current', response);

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

function readPricing(req, res, next) {
    return sendHandledRequest({
        method: 'get',
        url: `${req.config.api.directory}/subscription/pricing/`,
        source: req,
        label: 'read_subscription_pricing',
    })
        .then(response => {
            _.set(req.context, 'subscription.pricing', response);

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

function getPersons(req, res, next) {
    return sendHandledRequest({
        method: 'get',
        url: `${req.config.api.directory}/v11/subscription/persons/`,
        source: req,
        label: 'read_subscription_persons',
    })
        .then(response => {
            _.set(req.context, 'subscription.persons', response);

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

function pay(req, res, next) {
    return sendHandledRequest({
        method: 'post',
        url: `${req.config.api.directory}/subscription/pay/`,
        source: req,
        label: 'make_subscription_payment',
    })
        .then(response => {
            _.set(req.context, 'subscription.payment', {
                url: _.get(response, 'payment_url'),
            });

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

function createContract(req, res, next) {
    return sendHandledRequest({
        method: 'post',
        url: `${req.config.api.directory}/subscription/create-contract-info/`,
        source: req,
        timeout: 30000,
        label: 'create_subscription_contract',
    })
        .then(() => next ? next() : req)
        .catch(next);
}

function activatePromoCode(req, res, next) {
    return sendHandledRequest({
        method: 'post',
        url: `${req.config.api.directory}/subscription/promocodes/activate/`,
        source: req,
        label: 'activate_promocode',
    })
        .then(response => {
            req.context.promocode = response;

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

module.exports = {
    readState,
    readPricing,
    pay,
    createContract,
    activatePromoCode,
    getPersons,
};
