import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect } from 'react'
import { getStats } from '../lib/api'

export function useStats() {
  const queryClient = useQueryClient()

  // Subscribe to SSE updates once; invalidate both stats and tests on any update
  useEffect(() => {
    const es = new EventSource('/api/events')
    es.onmessage = (e) => {
      try {
        const data = JSON.parse(e.data)
        if (data.type === 'update') {
          queryClient.invalidateQueries({ queryKey: ['stats'] })
          queryClient.invalidateQueries({ queryKey: ['tests'] })
        }
      } catch { /* ignore malformed */ }
    }
    return () => es.close()
  }, [queryClient])

  return useQuery({ queryKey: ['stats'], queryFn: getStats, refetchInterval: 30_000 })
}
