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/servers', () => HttpResponse.json({ 
    servers: [
      { id: 'srv-1', name: 'worker-01', template: 'worker', provider: 'hetzner', ip_address: '192.168.1.10', status: 'active', created_at: '2025-01-15T10:30:00Z', updated_at: '2025-01-15T10:30:00Z' },
      { id: 'srv-2', name: 'worker-02', template: 'worker-db', provider: 'hetzner', ip_address: '192.168.1.11', status: 'active', created_at: '2025-01-14T08:00:00Z', updated_at: '2025-01-14T08:00:00Z' }
    ] 
  })),
]

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

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

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

  it('shows server information', async () => {
    const { default: Servers } = await import('../../src/pages/Servers')
    
    render(
      <QueryClientProvider client={queryClient}>
        <BrowserRouter>
          <Servers />
        </BrowserRouter>
      </QueryClientProvider>
    )
    
    await waitFor(() => {
      expect(screen.getByText('worker-01')).toBeInTheDocument()
    })
  })
})
