import { useInfiniteQuery } from 'react-query';

import { getCalibrations } from 'src/pages/dashboard/performance/services';
import { flatPages, getNextPage } from 'src/utils/pagination';

import { performanceKeys } from '../../../queries';
import {
  CALIBRATION_PAGE_SIZE,
  type CalibrationFilter,
  calibrationFilterToAnswered,
} from '../constants';

type UseCalibrationsParams = {
  cycleId: string | number;
  filter: CalibrationFilter;
};

const useCalibrations = ({ cycleId, filter }: UseCalibrationsParams) => {
  const answered = calibrationFilterToAnswered(filter);

  const query = useInfiniteQuery(
    performanceKeys.calibrations(cycleId, answered),
    ({ pageParam = 1 }) =>
      getCalibrations(cycleId, {
        page: pageParam - 1,
        limit: CALIBRATION_PAGE_SIZE,
        answered,
      }),
    {
      keepPreviousData: true,
      getNextPageParam: (lastPage, pages) =>
        getNextPage(lastPage.data.items.length, CALIBRATION_PAGE_SIZE, pages),
    },
  );

  return {
    ...query,
    items: flatPages(query.data),
    totalCount: query.data?.pages[0]?.data.count ?? 0,
  };
};

export default useCalibrations;
