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

import { useApiClient } from '@/lib/apiClient';

export default function useActivityFeed({
  showFullFeed = false,
}: {
  showFullFeed?: boolean;
}) {
  const pageSize = showFullFeed ? 10 : 6;
  const resultType = 'social_activity';
  const apiClient = useApiClient();

  const { data, isLoading, fetchNextPage, hasNextPage, isFetchingNextPage } =
    useInfiniteQuery({
      queryKey: ['activityFeed', showFullFeed],
      queryFn: ({ pageParam }: { pageParam?: string }) =>
        apiClient.POST('/api/social/following-feed', {
          body: {
            page_size: pageSize,
            start_feed_timestamp: pageParam,
            ranking_method: 'default',
            result_type: resultType,
          },
        }),
      getNextPageParam: (lastPage) => {
        // check if we got fewer items than requested (no more data)
        if (!lastPage?.data?.items || lastPage.data.items.length < pageSize) {
          return undefined; // no more pages
        }
        // use the last_item_timestamp for the next page
        return lastPage.data.last_item_timestamp;
      },
      initialPageParam: undefined,
    });

  // flatten all pages into a single array
  const activityFeedItems =
    data?.pages?.flatMap((page) => page?.data?.items || []) || [];

  return {
    activityFeedItems,
    isLoading,
    hasMore: hasNextPage,
    isLoadingMore: isFetchingNextPage,
    onLoadMore: fetchNextPage,
  };
}
