import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import '@testing-library/jest-dom/vitest'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { useQuery } from '@tanstack/react-query'
import { HealthContent } from './HealthContent'

vi.mock('@tanstack/react-query', () => ({ useQuery: vi.fn() }))

describe('HealthContent', () => {
  afterEach(cleanup)

  it('reorders adapters when the system header is activated', async () => {
    vi.mocked(useQuery).mockReturnValue({
      data: {
        adapters: [
          { id: 'zulu', interval: 30, lastPollDurationMs: 20, consecutiveErrors: 0, stale: false },
          { id: 'alpha', interval: 30, lastPollDurationMs: 10, consecutiveErrors: 0, stale: false },
        ],
      },
      isLoading: false,
      isError: false,
    } as ReturnType<typeof useQuery>)

    render(<HealthContent />)
    const table = screen.getByRole('table', { name: 'Collector adapter health' })
    const systems = () => within(table).getAllByRole('row').slice(1).map((row) => within(row).getAllByRole('cell')[0]?.textContent)
    expect(systems()).toEqual(['alpha', 'zulu'])

    fireEvent.click(within(table).getByRole('button', { name: /System/ }))
    await waitFor(() => expect(systems()).toEqual(['zulu', 'alpha']))
  })
})
