import { getCodeInfoList } from "@/lib/api/commonCode";
import { queryKeys } from "@/lib/queryKeys";
import { useInfiniteScroll } from "@/hooks/useInfiniteScroll";
import type { CodeInfoFilter } from "@/lib/schemas/commonCode";
import type { CodeInfo } from "@/types/commonCode";

/**
 * 그룹(code_info) 무한 스크롤
 */
export function useCodeInfoInfinite(filters?: CodeInfoFilter) {
  return useInfiniteScroll<CodeInfo, CodeInfoFilter>({
    queryKey: queryKeys.codeInfo.infiniteList(filters) as unknown as any[],
    queryFn: async ({ pageParam, ...params }) => {
      const pageSize = pageParam === 1 ? 20 : 10;
      const response = await getCodeInfoList({
        search: params?.search,
        is_active: params?.active,
        page: pageParam,
        size: pageSize,
      });
      return {
        data: response.data || [],
        total: response.total,
        currentPage: pageParam,
        pageSize,
      };
    },
    initialPageParam: 1,
    pageSize: 20,
    params: filters,
    staleTime: 5 * 60 * 1000,
    getNextPageParam: (lastPage, _allPages, lastPageParam) => {
      const currentPageSize = lastPageParam === 1 ? 20 : 10;
      if ((lastPage.data?.length || 0) < currentPageSize) return undefined;
      return lastPageParam + 1;
    },
  });
}
