module.exports = Self => {
    Self.remoteMethodCtx('corrective', {
        description: 'Creates a rectificated invoice in',
        accessType: 'WRITE',
        accepts: [{
            arg: 'id',
            type: 'number'
        }, {
            arg: 'invoiceReason',
            type: 'number',
        }, {
            arg: 'invoiceType',
            type: 'number',
        }, {
            arg: 'invoiceClass',
            type: 'number'
        }],
        returns: {
            type: 'number',
            root: true
        },
        http: {
            path: '/corrective',
            verb: 'POST'
        }
    });

    Self.corrective = async(ctx, id, invoiceReason, invoiceType, invoiceClass, options) => {
        const models = Self.app.models;
        const myOptions = {};
        let tx;

        if (typeof options == 'object')
            Object.assign(myOptions, options);

        if (!myOptions.transaction) {
            tx = await Self.beginTransaction({});
            myOptions.transaction = tx;
        }

        try {
            const clone = await Self.clone(ctx, id, true, myOptions);
            await models.InvoiceInCorrection.create({
                correctingFk: clone.id,
                correctedFk: id,
                cplusRectificationTypeFk: invoiceType,
                siiTypeInvoiceOutFk: invoiceClass,
                invoiceCorrectionTypeFk: invoiceReason
            }, myOptions);

            if (tx) await tx.commit();
            return clone.id;
        } catch (e) {
            if (tx) await tx.rollback();
            throw e;
        }
    };
};