import { createEventStream } from 'h3'
import { requireAuth } from '../../utils/authHelpers.js'
import { getActiveEntitiesInBbox } from '../../utils/cotStore.js'
import { registerSubscriber } from '../../utils/cotSubscribers.js'
import { getCotSnapshotOpts } from '../../utils/cotSnapshot.js'
import { COT_SSE_HEARTBEAT_MS } from '../../utils/constants.js'
import { parseBboxParam, parseLayersParam } from '../../utils/cotEntityUtils.js'
import { scheduleTrackingFeedRefresh } from '../../utils/trackingFeed.js'

export default defineEventHandler((event) => {
  requireAuth(event)
  const query = getQuery(event)
  const bbox = parseBboxParam(typeof query.bbox === 'string' ? query.bbox : undefined)
  const layers = parseLayersParam(typeof query.layers === 'string' ? query.layers : undefined)
  const snapshotOpts = getCotSnapshotOpts()

  const stream = createEventStream(event)

  const push = (eventName, data) => stream.push({ event: eventName, data })

  const sendSnapshot = async () => {
    const entities = await getActiveEntitiesInBbox(bbox, { ...snapshotOpts, layers })
    await push('snapshot', JSON.stringify({ entities }))
  }

  const unregister = registerSubscriber({ bbox, layers, push })

  let heartbeat

  stream.onClosed(async () => {
    clearInterval(heartbeat)
    unregister()
    scheduleTrackingFeedRefresh()
  })

  void (async () => {
    scheduleTrackingFeedRefresh()
    await sendSnapshot()
    heartbeat = setInterval(() => {
      push('heartbeat', '{}').catch(() => {})
    }, COT_SSE_HEARTBEAT_MS)
  })()

  return stream.send()
})
