import { onMounted, onBeforeUnmount, watch } from 'vue'
import type { Ref } from 'vue'
import { eventBus } from './eventBus'

export function useBackendEvents(userId: Ref<string>) {
  let eventSource: EventSource | null = null

  const connect = () => {
    if (eventSource) eventSource.close()
    if (userId.value) {
      console.log('Connecting to backend events for user:', userId.value)
      eventSource = new EventSource(`/events?user_id=${userId.value}`)

      eventSource.onmessage = (event) => {
        const data = JSON.parse(event.data)

        // Emit globally for any component that cares
        eventBus.emit(data.type, data)
        eventBus.emit('sse', data) // optional: catch-all channel
      }
    }
  }

  onMounted(connect)
  watch(userId, connect)
  onBeforeUnmount(() => {
    console.log('Disconnecting from backend events for user:', userId.value)
    eventSource?.close()
  })
}
