const models = require('vn-loopback/server/server').models;
const LoopBackContext = require('loopback-context');

describe('setSaleQuantity()', () => {
    beforeAll(async() => {
        const activeCtx = {
            accessToken: {userId: 9},
            http: {
                req: {
                    headers: {origin: 'http://localhost'}
                }
            }
        };
        spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
            active: activeCtx
        });
    });

    it('should change quantity sale', async() => {
        const tx = await models.Ticket.beginTransaction({});
        spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => {
            if (sqlStatement.includes('catalog_calcFromItem')) {
                sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY
                        SELECT 100 as available;`;
                params = null;
            }
            return models.Ticket.rawSql(sqlStatement, params, options);
        });

        try {
            const options = {transaction: tx};

            const saleId = 30;
            const newQuantity = 10;

            const originalSale = await models.Sale.findById(saleId, null, options);

            await models.Collection.setSaleQuantity(saleId, newQuantity, options);
            const updateSale = await models.Sale.findById(saleId, null, options);

            expect(updateSale.quantity).not.toEqual(originalSale.quantity);
            expect(updateSale.quantity).toEqual(newQuantity);

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