import { useState, useCallback } from "react";
import { supabase } from "@/integrations/supabase/client";

export function useDocumentSummary() {
  const [summarizing, setSummarizing] = useState<Record<string, boolean>>({});

  const generateSummary = useCallback(async (documentId: string, fileUrl: string, title: string) => {
    setSummarizing(prev => ({ ...prev, [documentId]: true }));
    try {
      const { data, error } = await supabase.functions.invoke("summarize-document", {
        body: { documentId, fileUrl, title },
      });
      if (error) throw error;
      return data?.summary || null;
    } catch (err) {
      console.error("Summary generation failed:", err);
      return null;
    } finally {
      setSummarizing(prev => ({ ...prev, [documentId]: false }));
    }
  }, []);

  const isSummarizing = useCallback((documentId: string) => {
    return !!summarizing[documentId];
  }, [summarizing]);

  return { generateSummary, isSummarizing };
}
