import { useQueries, useQuery } from "@tanstack/react-query";
import { extractUrls, type LinkMetadata } from "@/lib/link-metadata";
import { platform } from "@/lib/platform";

export function useLinkMetadata(url: string | null) {
  return useQuery<LinkMetadata | null>({
    queryKey: ["link-metadata", url],
    queryFn: () => platform.link.fetchMetadata(url!),
    enabled: !!url,
    staleTime: Infinity,
    gcTime: 30 * 60 * 1000,
    retry: 1,
  });
}

export function useFirstLinkMetadata(text: string) {
  const urls = extractUrls(text);
  const firstUrl = urls[0] ?? null;
  return { ...useLinkMetadata(firstUrl), url: firstUrl };
}

export interface LinkPreviewEntry {
  url: string;
  metadata: LinkMetadata | null | undefined;
  isLoading: boolean;
}

export function useAllLinkMetadata(text: string): LinkPreviewEntry[] {
  const urls = extractUrls(text);

  const results = useQueries({
    queries: urls.map((url) => ({
      queryKey: ["link-metadata", url],
      queryFn: () => platform.link.fetchMetadata(url),
      staleTime: Infinity,
      gcTime: 30 * 60 * 1000,
      retry: 1,
    })),
  });

  return urls.map((url, i) => ({
    url,
    metadata: results[i].data,
    isLoading: results[i].isLoading,
  }));
}
