import { createContext, useContext, useEffect, useState, type ReactNode } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { quoteKeys } from "./queries";

type SseStatus = "connecting" | "connected" | "disconnected";

const SseContext = createContext<SseStatus>("connecting");

export function useSseStatus() {
  return useContext(SseContext);
}

export function SseProvider({ children }: { children: ReactNode }) {
  const queryClient = useQueryClient();
  const [status, setStatus] = useState<SseStatus>("connecting");

  useEffect(() => {
    const MAX_RETRIES = 10;
    let retryCount = 0;
    let eventSource = new EventSource("/api/quotes/events");

    eventSource.addEventListener("quotes-updated", () => {
      queryClient.invalidateQueries({ queryKey: quoteKeys.all });
    });

    eventSource.onopen = () => {
      retryCount = 0;
      setStatus("connected");
    };

    eventSource.onerror = () => {
      setStatus("connecting");
      retryCount++;

      if (retryCount > MAX_RETRIES) {
        eventSource.close();
        setStatus("disconnected");
      }
    };

    return () => {
      eventSource.close();
    };
  }, [queryClient]);

  return (
    <SseContext.Provider value={status}>
      {children}
    </SseContext.Provider>
  );
}
