module.exports = Self => {
    Self.remoteMethod('delete', {
        description: 'Delete sale trackings and item shelving sales',
        accessType: 'WRITE',
        accepts: [
            {
                arg: 'saleFk',
                type: 'number',
                description: 'The sale id'
            },
            {
                arg: 'stateCodes',
                type: ['string']
            },
        ],
        http: {
            path: `/delete`,
            verb: 'POST'
        }
    });

    Self.delete = async(saleFk, stateCodes, 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 itemShelvingSales = await models.ItemShelvingSale.find({where: {saleFk: saleFk}}, myOptions);

            for (let itemShelvingSale of itemShelvingSales)
                await itemShelvingSale.destroy(myOptions);

            const states = await models.State.find({
                fields: ['id'],
                where: {
                    code: {inq: stateCodes}
                }
            }, myOptions);

            const stateIds = states.map(state => state.id);

            const filter = {
                where: {
                    saleFk: saleFk,
                    stateFk: {inq: stateIds}
                }
            };
            const saleTrackings = await models.SaleTracking.find(filter, myOptions);
            for (let saleTracking of saleTrackings)
                await saleTracking.destroy(myOptions);

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