const UserError = require('vn-loopback/util/user-error');

module.exports = Self => {
    Self.remoteMethod('removes', {
        description: 'Delete an Order Row',
        accessType: 'WRITE',
        accepts: [{
            arg: 'params',
            type: 'object',
            required: true,
            description: '[Row IDs], actualOrderId',
            http: {source: 'body'}
        }],
        returns: {
            type: 'string',
            root: true
        },
        http: {
            path: `/removes`,
            verb: 'post'
        }
    });

    Self.removes = async(params, options) => {
        const myOptions = {};
        let tx;

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

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

        try {
            if (!params.rows || !params.rows.length)
                throw new UserError('There is nothing to delete');

            const isEditable = await Self.app.models.Order.isEditable(params.actualOrderId, myOptions);

            if (!isEditable)
                throw new UserError('This order is not editable');

            const promises = [];
            for (let i = 0; i < params.rows.length; i++)
                promises.push(Self.app.models.OrderRow.destroyById(params.rows[i], myOptions));

            const deletions = await Promise.all(promises);

            if (tx) await tx.commit();

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