import { onEvent } from '$apps'
import { Hype } from '@because/hype'

const router = Hype.router()

// SSE: discrete lifecycle events for app processes (start, stop, deploy, etc.)
// Unlike /api/apps/stream (full state snapshots for the dashboard), this sends
// individual events so apps can react to specific lifecycle changes.
router.sse('/stream', (send) => {
  let queue = Promise.resolve()
  const safeSend = (...args: Parameters<typeof send>) => {
    queue = queue.then(() => send(...args))
  }
  const unsub = onEvent(event => safeSend(event))
  const heartbeat = setInterval(() => safeSend('', 'ping'), 60_000)
  return () => {
    clearInterval(heartbeat)
    unsub()
  }
})

export default router
