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

module.exports = Self => {
    Self.remoteMethodCtx('updateQuantity', {
        description: 'Changes the quantity of a sale',
        accessType: 'WRITE',
        accepts: [{
            arg: 'id',
            type: 'number',
            required: true,
            description: 'sale ID',
            http: {source: 'path'}
        }, {
            arg: 'quantity',
            type: 'number',
            required: true,
            description: 'newQuantity'
        }],
        returns: {
            type: 'string',
            root: true
        },
        http: {
            path: `/:id/updateQuantity`,
            verb: 'post'
        }
    });

    Self.updateQuantity = async(ctx, id, newQuantity, options) => {
        const models = Self.app.models;
        const $t = ctx.req.__; // $translate
        const myOptions = {};
        let tx;

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

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

        try {
            const canEditSale = await models.Sale.canEdit(ctx, [id], myOptions);

            if (!canEditSale)
                throw new UserError(`Sale(s) blocked, please contact production`);

            if (isNaN(newQuantity))
                throw new UserError(`The value should be a number`);

            const filter = {
                include: {
                    relation: 'ticket',
                    scope: {
                        include: {
                            relation: 'client',
                            scope: {
                                include: {
                                    relation: 'salesPersonUser',
                                    scope: {
                                        fields: ['id', 'name']
                                    }
                                }
                            }
                        }
                    }
                }
            };

            const sale = await models.Sale.findById(id, filter, myOptions);

            if (newQuantity > sale.quantity)
                throw new UserError('The new quantity should be smaller than the old one');

            const oldQuantity = sale.quantity;
            const result = await sale.updateAttributes({quantity: newQuantity}, myOptions);

            const salesPerson = sale.ticket().client().salesPersonUser();
            if (salesPerson) {
                const origin = ctx.req.headers.origin;
                const message = $t('Changed sale quantity', {
                    ticketId: sale.ticket().id,
                    itemId: sale.itemFk,
                    concept: sale.concept,
                    oldQuantity: oldQuantity,
                    newQuantity: newQuantity,
                    ticketUrl: `${origin}/#!/ticket/${sale.ticket().id}/sale`,
                    itemUrl: `${origin}/#!/item/${sale.itemFk}/summary`
                });
                await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions);
            }

            if (tx) await tx.commit();

            return result;
        } catch (error) {
            if (tx) await tx.rollback();
            throw error;
        }
    };
};