import { useInfiniteQuery } from "@tanstack/react-query";
import { apiSocialHubPostsCursor, hubPostsQueryKey } from "@/api/social/hubFeed";
import type { HubSortOption, HubTimeOption } from "@/api/social/hubFeed";

function extractCursor(nextUrl: string | null): string | null {
  if (!nextUrl) return null;
  try {
    const url = new URL(nextUrl, "http://placeholder");
    return url.searchParams.get("cursor");
  } catch {
    return null;
  }
}

interface Opts {
  hubId: number;
  sort?: HubSortOption;
  time?: HubTimeOption;
  start?: string;
  end?: string;
  enabled?: boolean;
}

export function useInfiniteHubPosts({ hubId, sort = "newest", time = "all", start, end, enabled = true }: Opts) {
  const query = useInfiniteQuery({
    queryKey: hubPostsQueryKey(hubId, sort, time, start, end),
    enabled: enabled && Number.isFinite(hubId),
    initialPageParam: null as string | null,
    queryFn: ({ pageParam, signal }) =>
      apiSocialHubPostsCursor({ hub: hubId, cursor: pageParam, sort, time, start, end }, signal),
    getNextPageParam: (last) => extractCursor(last.next),
  });

  const posts = query.data?.pages.flatMap((p) => p.results) ?? [];
  return { ...query, posts };
}
