module.exports = Self => {
    Self.remoteMethod('deleteItemShelvings', {
        description: 'Deletes the selected item shelvings',
        accessType: 'WRITE',
        accepts: [{
            arg: 'itemShelvingIds',
            type: ['number'],
            required: true,
            description: 'The itemShelving ids to delete'
        }],
        returns: {
            type: ['object'],
            root: true
        },
        http: {
            path: `/deleteItemShelvings`,
            verb: 'POST'
        }
    });

    Self.deleteItemShelvings = async(itemShelvingIds, 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 promises = [];
            for (let itemShelvingId of itemShelvingIds) {
                const itemShelvingSaleToDelete = models.ItemShelvingSale.destroyAll({
                    itemShelvingFk: itemShelvingId
                }, myOptions);
                promises.push(itemShelvingSaleToDelete);

                const itemShelvingToDelete = models.ItemShelving.destroyById(itemShelvingId, myOptions);
                promises.push(itemShelvingToDelete);
            }

            const deletedItemShelvings = await Promise.all(promises);

            if (tx) await tx.commit();

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