import { useInfiniteQuery } from "@tanstack/react-query";
import {
  apiSocialMessagesCursor,
  messagesQueryKey,
} 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 Opts {
  chatId: number;
  enabled?: boolean;
}

export function useInfiniteMessages({ chatId, enabled = true }: Opts) {
  const query = useInfiniteQuery({
    queryKey: messagesQueryKey(chatId),
    enabled: enabled && Number.isFinite(chatId),
    initialPageParam: null as string | null,
    queryFn: ({ pageParam, signal }) =>
      apiSocialMessagesCursor(
        { chat: chatId, cursor: pageParam ?? undefined },
        signal,
      ),
    getNextPageParam: (last) => extractCursor(last.next),
  });

  // Backend returns newest-first; reverse for chronological render.
  const messages = (query.data?.pages.flatMap((p) => p.results) ?? []).slice().reverse();

  return { ...query, messages };
}
