import { GetWantAPIComment, GetWantAPIEssay } from "@/type/wwwAPI";
import { wwwAPI } from "@/utilities/wwwAPI";
import { useInfiniteQuery } from "@tanstack/react-query";

export default function useGetWant(
  wantVariety: "essay" | "comment",
  wantInput?: string,
) {
  return useInfiniteQuery({
    enabled: !!wantInput,
    queryKey: ["want", wantVariety, wantInput],
    queryFn: async ({ pageParam }) => {
      const { data } = await wwwAPI.get<
        (GetWantAPIEssay | GetWantAPIComment)[]
      >(`/want/${wantVariety}/${wantInput}?page=${pageParam}`);
      return data;
    },
    initialPageParam: 1,
    initialData: {
      pages: [],
      pageParams: [1],
    },
    getNextPageParam: (lastPage, allPages, lastPageParam) => {
      return !lastPage || lastPage.length > 0 ? lastPageParam + 1 : undefined;
    },
    select: (data) => ({
      pages: data.pages.flatMap((page) => page),
      pageParams: data.pageParams,
    }),
  });
}
