"use client";

import { createContext, ReactNode, useContext } from "react";

import type { IChatMessage } from "@/entities/chats/types";
import { useChatSocket } from "@/hooks/chats/useChatSocket";

type ChatContextValue = ReturnType<typeof useChatSocket>;

const ChatContext = createContext<ChatContextValue | null>(null);

export function useChat() {
  const ctx = useContext(ChatContext);
  if (!ctx) {
    throw new Error("useChat must be used within <ChatProvider>");
  }
  return ctx;
}

interface ChatProviderProps {
  chatId: string;
  initialMessages?: IChatMessage[];
  initialTotal?: number;
  children: ReactNode;
}

export function ChatProvider({
  chatId,
  initialMessages,
  initialTotal,
  children,
}: ChatProviderProps) {
  const value = useChatSocket(chatId, {
    initialMessages,
    initialTotal,
  });

  return <ChatContext.Provider value={value}>{children}</ChatContext.Provider>;
}
