import { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest'
import { renderHook, waitFor } from '@testing-library/react'
import { http, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import React from 'react'
import { useUsersList } from '../../../features/users/hooks/useUsersList'

const API_URL = 'http://localhost:5000'

const server = setupServer()

beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))
afterEach(() => server.resetHandlers())
afterAll(() => server.close())

function createWrapper() {
  const qc = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
  return ({ children }: { children: React.ReactNode }) =>
    React.createElement(QueryClientProvider, { client: qc }, children)
}

describe('useUsersList', () => {
  it('fetches page 1 by default', async () => {
    server.use(
      http.get(`${API_URL}/api/v1/users`, () =>
        HttpResponse.json({ items: [{ id: 1, username: 'admin', nombre: 'Admin', apellido: 'S', email: null, rol: 'admin', activo: true, ultimoLogin: null }], page: 1, pageSize: 20, total: 1 }),
      ),
    )

    const { result } = renderHook(() => useUsersList({}), { wrapper: createWrapper() })
    await waitFor(() => expect(result.current.isSuccess).toBe(true))

    expect(result.current.data?.page).toBe(1)
    expect(result.current.data?.items).toHaveLength(1)
  })

  it('passes rol filter in query string', async () => {
    let capturedUrl: string | null = null
    server.use(
      http.get(`${API_URL}/api/v1/users`, ({ request }) => {
        capturedUrl = request.url
        return HttpResponse.json({ items: [], page: 1, pageSize: 20, total: 0 })
      }),
    )

    const { result } = renderHook(() => useUsersList({ rol: 'admin' }), { wrapper: createWrapper() })
    await waitFor(() => expect(result.current.isSuccess).toBe(true))

    expect(capturedUrl).toContain('rol=admin')
  })

  it('passes activo filter', async () => {
    let capturedUrl: string | null = null
    server.use(
      http.get(`${API_URL}/api/v1/users`, ({ request }) => {
        capturedUrl = request.url
        return HttpResponse.json({ items: [], page: 1, pageSize: 20, total: 0 })
      }),
    )

    const { result } = renderHook(() => useUsersList({ activo: false }), { wrapper: createWrapper() })
    await waitFor(() => expect(result.current.isSuccess).toBe(true))

    expect(capturedUrl).toContain('activo=false')
  })
})
