import { describe, it, expect, beforeAll, afterEach, afterAll } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { BrowserRouter } from 'react-router-dom'
import React from 'react'
import { http, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'

const handlers = [
  http.get('/api/v1/cluster/health', () => HttpResponse.json({
    healthy: true,
    total_servers: 12,
    active_servers: 10,
    error_servers: 1,
    services_up: 50,
    services_down: 2
  })),
]

const server = setupServer(...handlers)
beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close())

const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })

describe('Dashboard Integration Tests', () => {
  it('renders without crashing', async () => {
    const { default: Dashboard } = await import('../../src/pages/Dashboard')
    
    render(
      <QueryClientProvider client={queryClient}>
        <BrowserRouter>
          <Dashboard />
        </BrowserRouter>
      </QueryClientProvider>
    )
    
    await waitFor(() => {
      expect(screen.getByText('Total Servers')).toBeInTheDocument()
    })
  })

  it('displays stats correctly', async () => {
    const { default: Dashboard } = await import('../../src/pages/Dashboard')
    
    render(
      <QueryClientProvider client={queryClient}>
        <BrowserRouter>
          <Dashboard />
        </BrowserRouter>
      </QueryClientProvider>
    )
    
    await waitFor(() => {
      expect(screen.getByText('12')).toBeInTheDocument()
    })
  })
})
