import { getApiBase, getToken } from './client'

export function createSSE<T>(
  url: string,
  onMessage: (data: T) => void,
  onError?: (err: Event) => void,
): () => void {
  const prefixedUrl = getApiBase() + url
  const token = getToken()
  const fullUrl = token
    ? `${prefixedUrl}${prefixedUrl.includes('?') ? '&' : '?'}access_token=${encodeURIComponent(token)}`
    : prefixedUrl

  const source = new EventSource(fullUrl)

  source.onmessage = (e) => {
    try {
      const parsed = JSON.parse(e.data) as T
      onMessage(parsed)
    } catch { /* ignore parse errors */ }
  }

  source.onerror = (e) => {
    onError?.(e)
  }

  return () => source.close()
}
