import React from 'react';
import * as apollo from '@apollo/client';
import { render, fireEvent } from '@testing-library/react';
import { renderHook } from '@testing-library/react-hooks';
import { NrDeliveryJobStatus } from '../../../globalTypes';
import { useFulfillDeliveryJobsMutation } from '../fulfillNrDeliveryJobs';

describe('useFulfillDeliveryJobsMutation', () => {
    const buttonId = 'BTN';

    const TestApp = () => {
        const { fulfillDeliveryJob } = useFulfillDeliveryJobsMutation({
            jobIds: ['1', '2'],
            status: NrDeliveryJobStatus.COMPLETE,
        });

        return (
            <button
                type="button"
                data-testid={buttonId}
                onClick={async () => {
                    await fulfillDeliveryJob({
                        variables: {
                            jobIds: ['1', '2'],
                            status: NrDeliveryJobStatus.COMPLETE,
                        },
                    });
                }}
            />
        );
    };

    const renderWrapper = () => render(<TestApp />);

    const fulfillDeliveryJob = jest.fn();
    const mutationData = {
        fulfillNrDeliveryJobs: [{ id: 'uuid-1' }],
    };
    const mockMutation = (data: Partial<apollo.MutationResult>) =>
        jest
            .spyOn(apollo, 'useMutation')
            .mockReturnValue([
                fulfillDeliveryJob,
                data as apollo.MutationResult,
            ]);

    beforeEach(() => {
        mockMutation({ data: mutationData });
        fulfillDeliveryJob.mockClear();
    });

    test('executes mutation', () => {
        mockMutation({ data: mutationData });
        const { getByTestId } = renderWrapper();
        const btn = getByTestId(buttonId);
        fireEvent.click(btn);

        expect(fulfillDeliveryJob).toHaveBeenCalled();
        expect(fulfillDeliveryJob).toHaveBeenCalledTimes(1);
        expect(fulfillDeliveryJob).toHaveBeenCalledWith({
            variables: {
                jobIds: ['1', '2'],
                status: NrDeliveryJobStatus.COMPLETE,
            },
        });
    });

    test('returns jobIds', () => {
        mockMutation({ data: mutationData });
        const { result } = renderHook(() =>
            useFulfillDeliveryJobsMutation({
                jobIds: ['uuid-1'],
                status: NrDeliveryJobStatus.COMPLETE,
            })
        );
        const { data } = result.current;

        expect(data).toEqual([{ id: 'uuid-1' }]);
    });
});
