import { type InfiniteData, type QueryKey } from 'react-query';

import { type AxiosResponse } from 'axios';

import { queryClient } from 'src/config/react-query';
import { type PaginatedResponse } from 'src/utils/tableUtils';

import { learningCertificatesKeys } from '../queries';
import {
  type LearningCertificateListItem,
  type LearningCertificatesListItemsTransform,
} from '../types';

type LearningCertificatesListQueryData = InfiniteData<
  AxiosResponse<PaginatedResponse<LearningCertificateListItem>>
>;

export type LearningCertificatesListSnapshot = Array<
  [QueryKey, LearningCertificatesListQueryData | undefined]
>;

export const optimisticallyUpdateLearningCertificatesList = async (
  transform: LearningCertificatesListItemsTransform,
): Promise<LearningCertificatesListSnapshot> => {
  await queryClient.cancelQueries(learningCertificatesKeys.list.all());

  const previousQueries =
    queryClient.getQueriesData<LearningCertificatesListQueryData>(
      learningCertificatesKeys.list.all(),
    );

  previousQueries.forEach(([queryKey, data]) => {
    if (!data) return;

    queryClient.setQueryData(queryKey, {
      ...data,
      pages: data.pages.map(page => ({
        ...page,
        data: {
          ...page.data,
          items: transform(page.data.items),
        },
      })),
    });
  });

  return previousQueries;
};

export const restoreLearningCertificatesListQueries = (
  previousQueries: LearningCertificatesListSnapshot,
) => {
  previousQueries.forEach(([queryKey, data]) => {
    queryClient.setQueryData(queryKey, data);
  });
};
