import { ref, onUnmounted } from 'vue'
import { chatWs } from '../services/websocket'
import type { StreamEvent } from '../types'

export function useWebSocket() {
  const connected = ref(chatWs.connected)
  const lastEvent = ref<StreamEvent | null>(null)

  const unsubscribe = chatWs.onEvent((event) => {
    lastEvent.value = event
    connected.value = chatWs.connected
  })

  onUnmounted(() => {
    unsubscribe()
  })

  function send(question: string, conversationId?: string) {
    chatWs.send(question, conversationId)
  }

  return { connected, lastEvent, send }
}
