import React from 'react';
import * as apollo from '@apollo/client';
import { fireEvent, render } from '@testing-library/react';
import { renderHook } from '@testing-library/react-hooks';
import { PhysicalDeliveryOrderStatus } from 'src/data/globalTypes';
import { useUpdatePhysicalDeliveryOrdersMutation } from '../updatePhysicalDeliveryOrders';

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

    const TestApp = () => {
        const { updateOrders } = useUpdatePhysicalDeliveryOrdersMutation();

        return (
            <button
                type="button"
                data-testid={buttonId}
                onClick={async () => {
                    await updateOrders({
                        variables: {
                            input: [
                                {
                                    id: '123',
                                    status: PhysicalDeliveryOrderStatus.COMPLETE,
                                },
                            ],
                        },
                    });
                }}
            />
        );
    };
    const renderWrapper = () => render(<TestApp />);

    const updateOrders = jest.fn();
    const mutationData = {
        updatePhysicalDeliveryOrders: [{ id: '123' }],
    };
    const mockMutation = (data: Partial<apollo.MutationResult>) =>
        jest
            .spyOn(apollo, 'useMutation')
            .mockReturnValue([updateOrders, data as apollo.MutationResult]);

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

    afterEach(() => {
        updateOrders.mockClear();
    });

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

        expect(updateOrders).toHaveBeenCalled();
        expect(updateOrders).toHaveBeenCalledTimes(1);
        expect(updateOrders).toHaveBeenCalledWith({
            variables: {
                input: [
                    {
                        id: '123',
                        status: PhysicalDeliveryOrderStatus.COMPLETE,
                    },
                ],
            },
        });
    });

    test('returns orderIds', () => {
        const { result } = renderHook(() =>
            useUpdatePhysicalDeliveryOrdersMutation()
        );
        const { updateOrdersData } = result.current;

        expect(updateOrdersData).toEqual([{ id: '123' }]);
    });
});
