module.exports = Self => {
    Self.remoteMethodCtx('setDelivered', {
        description: 'Changes the state of the received ticket ids to delivered',
        accessType: 'WRITE',
        accepts: [
            {
                arg: 'ticketIds',
                description: 'the array of ticket ids to set as delivered',
                type: ['number'],
                required: true,
                http: {source: 'body'}
            }
        ],
        returns: {
            type: 'object',
            root: true
        },
        http: {
            path: `/setDelivered`,
            verb: 'POST'
        }
    });

    Self.setDelivered = async(ctx, ticketIds, options) => {
        const userId = ctx.req.accessToken.userId;
        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 state = await models.State.findOne({
                where: {
                    code: 'delivered'
                },
                fields: ['id', 'name', 'alertLevel', 'code']
            }, myOptions);

            const worker = await models.Worker.findOne({where: {userFk: userId}}, myOptions);

            const promises = [];
            for (const id of ticketIds) {
                const promise = models.TicketTracking.changeState(ctx, {
                    stateFk: state.id,
                    workerFk: worker.id,
                    ticketFk: id
                }, myOptions);
                promises.push(promise);
            }
            await Promise.all(promises);

            if (tx) await tx.commit();

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