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

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

const mockDetail = {
  id: 5,
  username: 'cajero1',
  nombre: 'Pedro',
  apellido: 'Gómez',
  email: 'new@x.com',
  rol: 'cajero',
  activo: true,
  mustChangePassword: false,
  ultimoLogin: null,
  fechaModificacion: '2026-04-15T18:00:00Z',
}

const server = setupServer()

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

describe('updateUser api client', () => {
  it('calls PUT /api/v1/users/:id with payload and returns updated UserDetail', async () => {
    let capturedBody: unknown = null
    server.use(
      http.put(`${API_URL}/api/v1/users/5`, async ({ request }) => {
        capturedBody = await request.json()
        return HttpResponse.json(mockDetail)
      }),
    )

    const result = await updateUser(5, {
      nombre: 'Pedro',
      apellido: 'Gómez',
      email: 'new@x.com',
      rol: 'cajero',
      activo: true,
    })

    expect(result.nombre).toBe('Pedro')
    expect(capturedBody).toMatchObject({ nombre: 'Pedro', apellido: 'Gómez', email: 'new@x.com' })
  })
})
