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

describe('Sale refund()', () => {
    const userId = 5;
    const ctx = {req: {accessToken: userId}};
    const activeCtx = {
        accessToken: {userId},
    };
    const servicesIds = [3];
    const withWarehouse = true;

    beforeEach(() => {
        spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
            active: activeCtx
        });
    });

    it('should create ticket with the selected lines', async() => {
        const tx = await models.Sale.beginTransaction({});
        const salesIds = [7, 8];

        try {
            const options = {transaction: tx};

            const refundedTicket = await models.Sale.refund(ctx, salesIds, servicesIds, withWarehouse, options);

            expect(refundedTicket).toBeDefined();

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

    it('should create one ticket for each unique ticketFk in the sales', async() => {
        const tx = await models.Sale.beginTransaction({});
        const salesIds = [6, 7];

        try {
            const options = {transaction: tx};

            const ticket = await models.Sale.refund(ctx, salesIds, servicesIds, withWarehouse, options);

            const refundedTicket = await models.Ticket.findOne({
                where: {
                    id: ticket.id
                },
                include: [
                    {
                        relation: 'ticketSales',
                        scope: {
                            include: {
                                relation: 'components'
                            }
                        }
                    },
                    {
                        relation: 'ticketServices',
                    }
                ]
            }, options);

            const salesLength = refundedTicket.ticketSales().length;
            const componentsLength = refundedTicket.ticketSales()[0].components().length;

            expect(refundedTicket).toBeDefined();
            expect(salesLength).toEqual(2);
            expect(componentsLength).toEqual(4);

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