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

module.exports = Self => {
    Self.remoteMethodCtx('moveExpeditions', {
        description: 'Move the selected expeditions to another ticket',
        accessType: 'WRITE',
        accepts: [{
            arg: 'clientId',
            type: 'number',
            description: `The client id`,
            required: true
        },
        {
            arg: 'landed',
            type: 'date',
            description: `The landing date`
        },
        {
            arg: 'warehouseId',
            type: 'number',
            description: `The warehouse id`,
            required: true
        },
        {
            arg: 'addressId',
            type: 'number',
            description: `The address id`,
            required: true
        },
        {
            arg: 'agencyModeId',
            type: 'any',
            description: `The agencyMode id`
        },
        {
            arg: 'routeId',
            type: 'any',
            description: `The route id`
        },
        {
            arg: 'expeditionIds',
            type: ['number'],
            required: true,
            description: 'The expeditions ids to move'
        }],
        returns: {
            type: 'object',
            root: true
        },
        http: {
            path: `/moveExpeditions`,
            verb: 'POST'
        }
    });

    Self.moveExpeditions = async(ctx, options) => {
        const models = Self.app.models;
        const args = ctx.args;
        const myOptions = {};
        let tx;

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

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

        try {
            if (args.routeId) {
                const route = await models.Route.findById(args.routeId, null, myOptions);
                if (!route) throw new UserError('This route does not exists');
            }
            const ticket = await models.Ticket.new(ctx, myOptions);
            const promises = [];
            for (let expeditionsId of args.expeditionIds) {
                const expeditionToUpdate = await models.Expedition.findById(expeditionsId, null, myOptions);
                const expeditionUpdated = expeditionToUpdate.updateAttribute('ticketFk', ticket.id, myOptions);
                promises.push(expeditionUpdated);
            }

            await Promise.all(promises);

            if (tx) await tx.commit();

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