import { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest'
import { http, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'
import { listUsers } from '../../../features/users/api/listUsers'

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

const mockPage1 = {
  items: [
    { id: 1, username: 'admin', nombre: 'Admin', apellido: 'Sistema', email: null, rol: 'admin', activo: true, ultimoLogin: null },
    { id: 2, username: 'cajero1', nombre: 'Juan', apellido: 'Pérez', email: 'j@x.com', rol: 'cajero', activo: true, ultimoLogin: '2026-04-10T10:00:00Z' },
  ],
  page: 1,
  pageSize: 20,
  total: 2,
}

const server = setupServer()

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

describe('listUsers api client', () => {
  it('calls GET /api/v1/users and returns PagedResult', async () => {
    server.use(
      http.get(`${API_URL}/api/v1/users`, () => HttpResponse.json(mockPage1)),
    )

    const result = await listUsers({})
    expect(result.items).toHaveLength(2)
    expect(result.page).toBe(1)
    expect(result.pageSize).toBe(20)
    expect(result.total).toBe(2)
  })

  it('passes query params: page, pageSize, rol, activo, search', 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 })
      }),
    )

    await listUsers({ page: 2, pageSize: 10, rol: 'cajero', activo: false, search: 'juan' })

    expect(capturedUrl).toContain('page=2')
    expect(capturedUrl).toContain('pageSize=10')
    expect(capturedUrl).toContain('rol=cajero')
    expect(capturedUrl).toContain('activo=false')
    expect(capturedUrl).toContain('search=juan')
  })

  it('omits undefined params from querystring', 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 })
      }),
    )

    await listUsers({ page: 1 })

    expect(capturedUrl).not.toContain('rol=')
    expect(capturedUrl).not.toContain('activo=')
    expect(capturedUrl).not.toContain('search=')
  })
})
