import { useInfiniteQuery } from "@tanstack/react-query";
import {
  apiSocialPostReplies,
  apiSocialPostsFeed,
  feedQueryKey,
  repliesQueryKey,
  type FeedStrategy,
} from "@/api/social/feed";

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 FeedOpts {
  strategy?: FeedStrategy;
  enabled?: boolean;
}

export function useInfinitePosts({ strategy = "recent", enabled = true }: FeedOpts = {}) {
  const query = useInfiniteQuery({
    queryKey: feedQueryKey({ feed_strategy: strategy }),
    enabled,
    initialPageParam: null as string | null,
    queryFn: ({ pageParam, signal }) =>
      apiSocialPostsFeed(
        { cursor: pageParam ?? undefined, feed_strategy: strategy },
        signal,
      ),
    getNextPageParam: (last) => extractCursor(last.next),
  });

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

interface RepliesOpts {
  postId: number;
  enabled?: boolean;
}

export function useInfiniteReplies({ postId, enabled = true }: RepliesOpts) {
  const query = useInfiniteQuery({
    queryKey: repliesQueryKey(postId),
    enabled: enabled && Number.isFinite(postId),
    initialPageParam: null as string | null,
    queryFn: ({ pageParam, signal }) =>
      apiSocialPostReplies({ reply_to: postId, cursor: pageParam ?? undefined }, signal),
    getNextPageParam: (last) => extractCursor(last.next),
  });

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