import { createGlobalState } from '@vueuse/core'

export interface ChatClientMessage {
  text: string
  replyTo?: {
    messageId: string
  }
}

export interface ChatMessage {
  id: string
  sender: string
  text: string
  createdAt: string
  replyTo?: {
    messageId: string
    sender: string
    text: string
  }
}

export const useChat = createGlobalState(() => {
  const signaling = useSignaling()
  const { emit } = useEventBus()

  const messages = shallowRef<ChatMessage[]>([])

  watch(signaling.socket, (socket) => {
    if (!socket)
      return

    socket.on('chat:new-message', (message: ChatMessage) => {
      messages.value.push(message)
      triggerRef(messages)

      emit('chat:new-message')
    })

    socket.on('disconnect', () => {
      messages.value = []
    })
  }, { immediate: true, flush: 'sync' })

  function sendMessage(message: ChatClientMessage) {
    if (!signaling.connected.value)
      return

    message.text = message.text.trim()

    if (!message.text.length)
      return

    signaling.socket.value!.emit('chat:message', message)
  }

  return {
    messages,
    sendMessage,
  }
})
