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

    Self.updatePrice = async(ctx, id, newPrice, options) => {
        const $t = ctx.req.__; // $translate
        const models = Self.app.models;
        const myOptions = {userId: ctx.req.accessToken.userId};
        let tx;

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

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

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

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

            await models.Sale.canEdit(ctx, [id], myOptions);

            const oldPrice = sale.price;
            const userId = ctx.req.accessToken.userId;

            const usesMana = await models.Sale.usesMana(ctx, myOptions);
            const componentCode = usesMana ? 'mana' : 'buyerDiscount';
            const discount = await models.Component.findOne({where: {code: componentCode}}, myOptions);
            const componentId = discount.id;
            const componentValue = newPrice - sale.price;

            const where = {
                componentFk: componentId,
                saleFk: id
            };
            const saleComponent = await models.SaleComponent.findOne({where}, myOptions);
            if (saleComponent) {
                await models.SaleComponent.updateAll(where, {
                    value: saleComponent.value + componentValue
                }, myOptions);
            } else {
                await models.SaleComponent.create({
                    saleFk: id,
                    componentFk: componentId,
                    value: componentValue
                }, myOptions);
            }

            const [priceFixed] = await Self.rawSql(`
                SELECT SUM(value) value
                    FROM sale s
                        JOIN saleComponent sc ON sc.saleFk = s.id
                        JOIN component c ON c.id = sc.componentFk
                        JOIN componentType ct ON ct.id = c.typeFk
                    WHERE ct.isBase
                        AND s.id = ?
            `, [id], myOptions);

            await sale.updateAttributes({
                price: newPrice,
                priceFixed: priceFixed.value
            }, myOptions);

            await Self.rawSql('CALL vn.manaSpellersRequery(?)', [userId], myOptions);
            await Self.rawSql('CALL vn.ticket_recalc(?, NULL)', [sale.ticketFk], myOptions);

            const salesPerson = sale.ticket().client().salesPersonUser();
            if (salesPerson) {
                const url = await Self.app.models.Url.getUrl();
                const message = $t('Changed sale price', {
                    ticketId: sale.ticket().id,
                    itemId: sale.itemFk,
                    concept: sale.concept,
                    quantity: sale.quantity,
                    oldPrice: oldPrice,
                    newPrice: newPrice,
                    ticketUrl: `${url}ticket/${sale.ticket().id}/sale`,
                    itemUrl: `${url}item/${sale.itemFk}/summary`
                });
                await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions);
            }

            if (tx) await tx.commit();

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