import { io, type Socket } from "socket.io-client";
import type { SupportConversation, SupportMessage } from "~/types";

type SupportRealtimePayload = {
  conversation: SupportConversation;
  message?: SupportMessage;
};

export function useSupportRealtime() {
  const socket = useState<Socket | null>("support-realtime-socket", () => null);
  const { token } = useAuth();
  const config = useRuntimeConfig();

  const connect = () => {
    if (!process.client || !token.value) {
      return null;
    }

    if (socket.value?.connected) {
      return socket.value;
    }

    if (socket.value) {
      socket.value.auth = { token: token.value };
      socket.value.connect();
      return socket.value;
    }

    const nextSocket = io(config.public.chatApiBase, {
      transports: ["websocket", "polling"],
      withCredentials: true,
      auth: {
        token: token.value
      }
    });

    socket.value = nextSocket;
    return nextSocket;
  };

  const disconnect = () => {
    socket.value?.disconnect();
  };

  const onConversationUpdated = (handler: (payload: SupportRealtimePayload) => void) => {
    const activeSocket = connect();
    activeSocket?.on("support:conversation.updated", handler);

    return () => {
      activeSocket?.off("support:conversation.updated", handler);
    };
  };

  const onMessageCreated = (handler: (payload: SupportRealtimePayload) => void) => {
    const activeSocket = connect();
    activeSocket?.on("support:message.created", handler);

    return () => {
      activeSocket?.off("support:message.created", handler);
    };
  };

  return {
    socket,
    connect,
    disconnect,
    onConversationUpdated,
    onMessageCreated
  };
}
