import React from 'react';
import * as apollo from '@apollo/client';
import { fireEvent, waitFor } from '@testing-library/react';
import { renderInAppContext } from '@theorchard/suite-testing';
import RightsInfo, { CLASSNAME } from '../rightsInfo';

describe('<TrackMetadata>', () => {
    const renderComponent = () => renderInAppContext(<RightsInfo songId="12345" />);

    const updateSong = jest.fn(() => Promise.resolve({}));

    beforeEach(() => {
        jest.spyOn(apollo, 'useMutation').mockReturnValue([
            updateSong,
            {
                data: { id: '' },
                loading: false,
                error: undefined
            } as apollo.MutationResult
        ]);
    });

    afterEach(() => {
        jest.clearAllMocks();
    });

    test('render RightsInfo component', () => {
        const component = renderComponent();
        const rightsInfo = component.getByTestId(CLASSNAME);

        expect(rightsInfo).toBeVisible();
    });

    test('executes updateNrSoundRecording after pressing submit', async () => {
        const { container } = renderComponent();

        const durationField = container.querySelectorAll('input[name="recordingYear"]').item(0);
        if (durationField)
            fireEvent.change(durationField, { target: { value: '2021' } });

        const submit = container.getElementsByClassName(`${CLASSNAME}-next-button`).item(0);
        if (submit)
            fireEvent.submit(submit);

        await waitFor(() => expect(updateSong).toHaveBeenCalledWith({
            variables: {
                id: '12345',
                recordingYear: 2021
            }
        }));
    });
});
