/** @vitest-environment jsdom */
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, cleanup, render } from '@testing-library/react'
import { createElement } from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { Delta, StateResponse } from '../../lib/collector-types'
import { CollectorRealtimeBridge } from './CollectorRealtimeBridge'

let onMessage: ((delta: Delta) => void) | undefined

vi.mock('@overdeck/deck-ui', () => ({
  useSseStream: vi.fn((options: { onMessage: (delta: Delta) => void }) => {
    onMessage = options.onMessage
  }),
}))

afterEach(() => {
  cleanup()
  onMessage = undefined
  vi.clearAllMocks()
})

describe('CollectorRealtimeBridge', () => {
  it('normalizes stale null collections before merging a panel delta', () => {
    const client = new QueryClient()
    client.setQueryData(['collector-state'], { panels: null, adapters: null })
    render(createElement(QueryClientProvider, { client }, createElement(CollectorRealtimeBridge)))
    const panel = { id: 'factory-runs', ts: '2026-08-09T12:00:00.000Z', data: { runs: [] } }

    act(() => onMessage?.({ type: 'panel', panel }))

    expect(client.getQueryData<StateResponse>(['collector-state'])).toEqual({ panels: [panel], adapters: [] })
  })
})
