import { ref, onUnmounted } from 'vue'

const HUB_URL = 'https://msg.gigafibre.ca'

/**
 * SSE composable for real-time Communication events from targo-hub.
 */
export function useSSE (opts = {}) {
  const connected = ref(false)
  let es = null
  let reconnectTimer = null
  let reconnectDelay = 1000

  function connect (topics) {
    disconnect()
    if (!topics || !topics.length) return

    const url = `${HUB_URL}/sse?topics=${encodeURIComponent(topics.join(','))}`
    es = new EventSource(url)

    es.onopen = () => {
      connected.value = true
      reconnectDelay = 1000
    }

    es.addEventListener('message', (e) => {
      try {
        const data = JSON.parse(e.data)
        if (opts.onMessage) opts.onMessage(data)
      } catch {}
    })

    es.addEventListener('sms-incoming', (e) => {
      try {
        const data = JSON.parse(e.data)
        if (opts.onSmsIncoming) opts.onSmsIncoming(data)
      } catch {}
    })

    es.onerror = () => {
      connected.value = false
      if (es && es.readyState === EventSource.CLOSED) {
        scheduleReconnect(topics)
      }
    }
  }

  function scheduleReconnect (topics) {
    if (reconnectTimer) clearTimeout(reconnectTimer)
    reconnectTimer = setTimeout(() => {
      reconnectDelay = Math.min(reconnectDelay * 2, 30000)
      connect(topics)
    }, reconnectDelay)
  }

  function disconnect () {
    if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null }
    if (es) { es.close(); es = null }
    connected.value = false
  }

  onUnmounted(disconnect)

  return { connect, disconnect, connected }
}
