import { describe, it, expect, beforeEach } from 'vitest'
import { screen, waitFor } from '@testing-library/react'
import { http, HttpResponse } from 'msw'
import { server } from '@/test/mocks/server'
import { renderWithProviders } from '@/test/utils'
import { AdminAuditPage } from '@/pages/AdminAuditPage'

describe('AdminAuditPage', () => {
  beforeEach(() => {
    localStorage.setItem('access_token', 'test-token')
  })

  it('renders audit log entries', async () => {
    renderWithProviders(<AdminAuditPage />)

    await waitFor(() => {
      // mockAuditLogEntry has action 'case.update'
      expect(screen.getByText('case.update')).toBeInTheDocument()
    })

    // Should show entity info: entity_type 'case' + entity_id '1'
    expect(screen.getByText('case #1')).toBeInTheDocument()

    // Should show user_id = 1
    expect(screen.getByText('1')).toBeInTheDocument()

    // Should show the IP address
    expect(screen.getByText('10.10.181.104')).toBeInTheDocument()
  })

  it('shows filter controls', async () => {
    renderWithProviders(<AdminAuditPage />)

    // Filter section title
    expect(screen.getByText('Filter')).toBeInTheDocument()

    // Filter input labels
    expect(screen.getByLabelText('Benutzer-ID')).toBeInTheDocument()
    expect(screen.getByLabelText('Aktion')).toBeInTheDocument()
    expect(screen.getByLabelText('Datum von')).toBeInTheDocument()
    expect(screen.getByLabelText('Datum bis')).toBeInTheDocument()

    // Filter buttons
    expect(screen.getByText('Filtern')).toBeInTheDocument()
    expect(screen.getByText('Zurücksetzen')).toBeInTheDocument()
  })

  it('handles empty audit log list', async () => {
    server.use(
      http.get('/api/admin/audit-log', () => {
        return HttpResponse.json([])
      }),
    )

    renderWithProviders(<AdminAuditPage />)

    await waitFor(() => {
      expect(screen.getByText('Keine Audit-Einträge gefunden.')).toBeInTheDocument()
    })
  })

  it('shows loading state', () => {
    // Delay the API response to observe loading state
    server.use(
      http.get('/api/admin/audit-log', async () => {
        await new Promise((resolve) => setTimeout(resolve, 500))
        return HttpResponse.json([])
      }),
    )

    renderWithProviders(<AdminAuditPage />)

    // The heading is always visible
    expect(screen.getByText('Audit-Log')).toBeInTheDocument()

    // During loading, neither the empty message nor table data should appear
    expect(screen.queryByText('Keine Audit-Einträge gefunden.')).not.toBeInTheDocument()
    expect(screen.queryByText('case.update')).not.toBeInTheDocument()
  })
})
