import { useQuery } from "@tanstack/react-query";
import { api } from "../lib/api";
import type { ChatMessage } from "../lib/webrtc";

interface ChatHistoryResponse {
  success: boolean;
  messages: ChatMessage[];
  count: number;
  error?: string;
}

export const useChatHistory = (sessionId: string | undefined, enabled = true) => {
  console.log("[useChatHistory] Hook called with:", { sessionId, enabled, willExecute: enabled && !!sessionId });
  
  return useQuery({
    queryKey: ["chat-history", sessionId],
    queryFn: async () => {
      console.log("[useChatHistory] Fetching chat history for session:", sessionId);
      
      if (!sessionId) {
        console.error("[useChatHistory] Session ID is required but not provided");
        throw new Error("Session ID is required");
      }

      try {
        console.log("[useChatHistory] Making API request to:", `sessions/${sessionId}/messages`);
        const response = await api
          .get(`sessions/${sessionId}/messages`)
          .json<ChatHistoryResponse>();

        console.log("[useChatHistory] API response:", response);

        if (!response.success) {
          console.error("[useChatHistory] API returned error:", response.error);
          throw new Error(response.error || "Failed to load chat history");
        }

        console.log("[useChatHistory] Successfully loaded", response.messages.length, "messages");
        return response.messages;
      } catch (error) {
        console.error("[useChatHistory] Error fetching chat history:", error);
        throw error;
      }
    },
    enabled: enabled && !!sessionId,
    staleTime: 1000 * 60 * 5, // 5 минут - история считается актуальной
    gcTime: 1000 * 60 * 30, // 30 минут в кэше
    refetchOnWindowFocus: false, // Не перезагружать при фокусе
    refetchOnReconnect: false, // Не перезагружать при реконнекте
  });
};

