"use client";

import { useCallback } from "react";
import { SessionProvider, useSession } from "next-auth/react";
import { ThemeProvider } from "@limitless/ui";
import { ChatProvider } from "@gsc/chat";

interface ProvidersProps {
  children: React.ReactNode;
  accessToken?: string | null;
}

function ChatProviderWrapper({ children }: { children: React.ReactNode }) {
  const { data: session } = useSession();

  const getToken = useCallback(async () => {
    return (session?.user as { accessToken?: string } | undefined)?.accessToken ?? null;
  }, [session]);

  return (
    <ChatProvider getToken={getToken}>
      {children}
    </ChatProvider>
  );
}

export default function Providers({ children, accessToken }: ProvidersProps) {
  return (
    <SessionProvider refetchInterval={4 * 60}>
      <ThemeProvider>
        <ChatProviderWrapper>
          {children}
        </ChatProviderWrapper>
      </ThemeProvider>
    </SessionProvider>
  );
}
