import { describe, it, expect } from 'vitest'
import { waitFor } from '@testing-library/react'
import { http, HttpResponse } from 'msw'
import { server } from '@/test/mocks/server'
import { renderHookWithProviders } from '@/test/utils'
import { mockDashboardResponse } from '@/test/mocks/data'
import { useDashboard } from '@/hooks/useDashboard'

describe('useDashboard', () => {
  it('fetches dashboard data for the given year', async () => {
    const { result } = renderHookWithProviders(() => useDashboard(2026))

    await waitFor(() => expect(result.current.isSuccess).toBe(true))

    expect(result.current.data).toEqual(mockDashboardResponse)
    expect(result.current.data!.kpis.total_cases).toBe(142)
    expect(result.current.data!.weekly).toHaveLength(6)
  })

  it('includes the year parameter in the API call', async () => {
    let capturedJahr: string | null = null

    server.use(
      http.get('/api/reports/dashboard', ({ request }) => {
        const url = new URL(request.url)
        capturedJahr = url.searchParams.get('jahr')
        return HttpResponse.json(mockDashboardResponse)
      }),
    )

    const { result } = renderHookWithProviders(() => useDashboard(2025))

    await waitFor(() => expect(result.current.isSuccess).toBe(true))

    expect(capturedJahr).toBe('2025')
  })

  it('handles server error (500)', async () => {
    server.use(
      http.get('/api/reports/dashboard', () => {
        return new HttpResponse(null, { status: 500 })
      }),
    )

    const { result } = renderHookWithProviders(() => useDashboard(2026))

    await waitFor(() => expect(result.current.isError).toBe(true))

    expect(result.current.data).toBeUndefined()
  })
})
