import { queryClient } from 'src/config/react-query';
import { Comment } from 'src/types/comments';

import {
  marketplaceKeys,
  unshiftLastCommentDataMarketplaceList,
} from './queries';

describe('marketplace queries', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });

  test('unshiftLastCommentDataMarketplaceList initializes null lastComments', () => {
    const setQueryDataSpy = jest.spyOn(queryClient, 'setQueryData');
    const comment = { id: 999 } as Comment;

    unshiftLastCommentDataMarketplaceList(10, comment);

    expect(setQueryDataSpy).toHaveBeenCalledTimes(1);

    const [queryKey, updater] = setQueryDataSpy.mock.calls[0];
    expect(queryKey).toEqual(marketplaceKeys.list());

    const oldData = {
      pages: [
        {
          data: [{ id: 10, lastComments: null }],
        },
      ],
    } as any;

    const updatedData = (updater as (data: any) => any)(oldData);
    expect(updatedData.pages[0].data[0].lastComments).toEqual([comment]);
  });

  test('unshiftLastCommentDataMarketplaceList prepends comment when list exists', () => {
    const setQueryDataSpy = jest.spyOn(queryClient, 'setQueryData');
    const previousComment = { id: 1 } as Comment;
    const newComment = { id: 2 } as Comment;

    unshiftLastCommentDataMarketplaceList(10, newComment);

    const updater = setQueryDataSpy.mock.calls[0][1] as (data: any) => any;

    const oldData = {
      pages: [
        {
          data: [{ id: 10, lastComments: [previousComment] }],
        },
      ],
    } as any;

    const updatedData = updater(oldData);
    expect(updatedData.pages[0].data[0].lastComments).toEqual([
      newComment,
      previousComment,
    ]);
  });
});
