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

describe('sale refund()', () => {
    const userId = 5;
    const activeCtx = {
        accessToken: {userId: userId},
    };

    const servicesIds = [3];

    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 response = await models.Sale.refund(salesIds, servicesIds, options);

            expect(response.length).toBeGreaterThanOrEqual(1);

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

    it('should create a 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 tickets = await models.Sale.refund(salesIds, servicesIds, options);

            const ticketsIds = tickets.map(ticket => ticket.id);

            const refundedTickets = await models.Ticket.find({
                where: {
                    id: {
                        inq: ticketsIds
                    }
                },
                include: [
                    {
                        relation: 'ticketSales',
                        scope: {
                            include: {
                                relation: 'components'
                            }
                        }
                    },
                    {
                        relation: 'ticketServices',
                    }
                ]
            }, options);

            const firstRefoundedTicket = refundedTickets[0];
            const secondRefoundedTicket = refundedTickets[1];
            const salesLength = firstRefoundedTicket.ticketSales().length;
            const componentsLength = firstRefoundedTicket.ticketSales()[0].components().length;
            const servicesLength = secondRefoundedTicket.ticketServices().length;

            expect(refundedTickets.length).toEqual(2);
            expect(salesLength).toEqual(1);
            expect(componentsLength).toEqual(4);
            expect(servicesLength).toBeGreaterThanOrEqual(1);

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