import { useInfiniteQuery } from "@tanstack/react-query";

import { wwwAXIOS } from "src/Www";
import { GetWantAPI } from "src/wwwAPI";

export default function useGetWant(
  wantVariety: "essay" | "comment",
  wantInput: string,
) {
  return useInfiniteQuery({
    queryKey: ["want", wantVariety, wantInput],
    queryFn: async ({ pageParam }) => {
      const { data } = await wwwAXIOS.get<GetWantAPI>(
        `/want/${wantVariety}/${wantInput}/${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,
    }),
  });
}
