import { useInfiniteQuery, useMutation, useQuery } from '@tanstack/react-query';
import { homeKeys } from '@/lib/query-keys';
import { GetMeetListRequest, homeService } from '@/services/home';

type PageParam = number | { page: number; exList: number[] };

export function useGetMeetList(params: Omit<GetMeetListRequest, 'pn'>, enabled: boolean = true) {
  return useInfiniteQuery({
    queryKey: homeKeys.getMeetList(params),
    queryFn: ({ pageParam }: { pageParam: PageParam }) => {
      // pageParam 可能是数字（第一页）或对象（后续页面包含 exList）
      const page = typeof pageParam === 'number' ? pageParam : pageParam.page;
      const exList =
        typeof pageParam === 'object' && pageParam !== null ? pageParam.exList : undefined;

      return homeService.getMeetList({
        ...params,
        pn: page,
        ...(exList && { exList }),
      });
    },
    initialPageParam: 1 as PageParam,
    getNextPageParam: (lastPage, allPages) => {
      // 如果最后一页的数据数量少于每页大小，说明没有更多数据了
      if (lastPage.length < params.ps) {
        return undefined;
      }

      // 收集所有已获取的 aiId 作为下一页的排除列表
      const exList: number[] = [];

      // 首先添加初始传入的 exList（如果有的话）
      if (params.exList && Array.isArray(params.exList)) {
        exList.push(...params.exList);
      }

      // 然后添加所有已获取页面的 aiId
      for (const page of allPages) {
        for (const item of page) {
          if (item.aiId) {
            exList.push(item.aiId);
          }
        }
      }

      return { page: allPages.length + 1, exList } as PageParam;
    },
    enabled, // 控制是否启用查询
  });
}

export function useGetChatRank() {
  return useQuery({
    queryKey: homeKeys.getChatRank(),
    queryFn: homeService.getChatRank,
  });
}

export function useGetHeartbeatRank() {
  return useQuery({
    queryKey: homeKeys.getHeartbeatRank(),
    queryFn: homeService.getHeartbeatRank,
  });
}

export function useGetGiftRank() {
  return useQuery({
    queryKey: homeKeys.getGiftRank(),
    queryFn: homeService.getGiftRank,
  });
}

export function useGetSevenDaysSignList() {
  return useQuery({
    queryKey: homeKeys.getSevenDaysSignList(),
    queryFn: homeService.getSevenDaysSignList,
  });
}

export function useSignIn() {
  return useMutation({
    mutationFn: homeService.signIn,
  });
}

export function useGetExplore() {
  return useQuery({
    queryKey: homeKeys.getExplore(),
    queryFn: homeService.getExplore,
  });
}

export function useGetHomeAiCarouselList() {
  return useQuery({
    queryKey: homeKeys.getHomeAiCarouselList(),
    queryFn: homeService.getHomeAiCarouselList,
  });
}

export function useGetHomeAggregateRecommend() {
  return useQuery({
    queryKey: homeKeys.getHomeAggregateRecommend(),
    queryFn: homeService.getHomeAggregateRecommend,
  });
}
