import './index.js';

describe('Entry buy', () => {
    let controller;
    let $httpBackend;

    beforeEach(ngModule('entry'));

    beforeEach(angular.mock.inject(($componentController, $compile, $rootScope, _$httpParamSerializer_, _$httpBackend_) => {
        $httpBackend = _$httpBackend_;
        let $element = $compile('<vn-entry-buy-index></vn-entry-buy-index')($rootScope);
        controller = $componentController('vnEntryBuyIndex', {$element});
        const params = _$httpParamSerializer_({filter: {limit: 20}});
        $httpBackend.whenGET(`Entries//getBuys?${params}`).respond([{id: 1}]);
    }));

    describe('saveBuy()', () => {
        it(`should call the buys patch route if the received buy has an ID`, () => {
            const buy = {id: 1, itemFk: 1, quantity: 1, packageFk: 1};

            const query = `Buys/${buy.id}`;

            $httpBackend.expectPATCH(query).respond(200);
            controller.saveBuy(buy);
            $httpBackend.flush();
        });

        it(`should call the entry addBuy post route if the received buy has no ID`, () => {
            controller.entry = {id: 1};
            const buy = {itemFk: 1, quantity: 1, packageFk: 1};

            const query = `Entries/${controller.entry.id}/addBuy`;

            $httpBackend.expectPOST(query).respond(200);
            controller.saveBuy(buy);
            $httpBackend.flush();
        });
    });

    describe('deleteBuys()', () => {
        it(`should perform no queries if all buys to delete were not actual instances`, () => {
            controller.buys = [
                {checked: true},
                {checked: true},
                {checked: false}];

            controller.deleteBuys();

            expect(controller.buys.length).toEqual(1);
        });

        it(`should perform a query to delete as there's an actual instance at least`, () => {
            controller.buys = [
                {checked: true, id: 1},
                {checked: true},
                {checked: false}];

            const query = 'Buys/deleteBuys';

            $httpBackend.expectPOST(query).respond(200);
            controller.deleteBuys();
            $httpBackend.flush();

            expect(controller.buys.length).toEqual(1);
        });
    });
});