module.exports = Self => {
    Self.remoteMethod('setSaleQuantity', {
        description: 'Update sale quantity',
        accessType: 'WRITE',
        accepts: [{
            arg: 'saleId',
            type: 'number',
            required: true,
            description: 'The sale id'
        },
        {
            arg: 'quantity',
            type: 'number',
            required: true,
            description: 'The quantity to picked'
        }],
        returns: {
            type: 'object',
            root: true
        },
        http: {
            path: `/setSaleQuantity`,
            verb: 'POST'
        }
    });

    Self.setSaleQuantity = async(saleId, quantity, 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 sale = await models.Sale.findById(saleId, null, myOptions);
            const saleUpdated = await sale.updateAttributes({
                quantity
            }, myOptions);

            if (tx) await tx.commit();

            return saleUpdated;
        } catch (e) {
            if (tx) await tx.rollback();
            throw e;
        }
    };
};