import { useInfiniteQuery } from '@tanstack/react-query';
import { reviewsApi } from '../apis';
import { reviewKeys } from '../keys';
import { NURSE_REVIEWS_STALE_TIME, REVIEWS_GC_TIME, REVIEWS_PAGE_SIZE } from '../constants';

/**
 * The nurse's **public** reviews list — the rating aggregate + an infinite, load-more list of **published**
 * reviews. Infinite paging keeps every loaded page in one cache entry keyed on the nurse id, so revisiting a
 * profile never refetches and "load more" appends without a setState-in-effect. The aggregate rides on every
 * page (same value) — read it off the first page. Never returns/renders non-published content (server
 * invariant); a submitted `pending_moderation` review is **never** injected here.
 */
export function useNurseReviews(nurseProfileId: number | undefined) {
  return useInfiniteQuery({
    queryKey: reviewKeys.nurse(nurseProfileId ?? -1),
    queryFn: ({ pageParam }) =>
      reviewsApi.getNurseReviews(nurseProfileId as number, { page: pageParam, pageSize: REVIEWS_PAGE_SIZE }),
    initialPageParam: 1,
    getNextPageParam: (lastPage) => {
      const { page, pageSize, total } = lastPage.reviews;
      return page * pageSize < total ? page + 1 : undefined;
    },
    enabled: nurseProfileId != null,
    staleTime: NURSE_REVIEWS_STALE_TIME,
    gcTime: REVIEWS_GC_TIME,
  });
}
