/**
 * users API 契约测试
 */
import { describe, it, expect, vi, beforeEach } from 'vitest'

const mockGet = vi.fn()
const mockPost = vi.fn()
const mockPut = vi.fn()
const mockDelete = vi.fn()

vi.mock('./client', () => ({
  default: {
    get: (...args: unknown[]) => mockGet(...args),
    post: (...args: unknown[]) => mockPost(...args),
    put: (...args: unknown[]) => mockPut(...args),
    delete: (...args: unknown[]) => mockDelete(...args),
  },
}))

import * as usersApi from './users'

beforeEach(() => {
  vi.clearAllMocks()
})

describe('users API', () => {
  const fakeRes = { data: { success: true, data: {} } }

  it('listUsers 应调用 GET /users 并传递分页和搜索参数', async () => {
    mockGet.mockResolvedValue(fakeRes)
    await usersApi.listUsers(2, 10, '张')

    expect(mockGet).toHaveBeenCalledWith('/users', {
      params: { page: 2, page_size: 10, search: '张' },
    })
  })

  it('listUsers 空搜索时应传 search 为 undefined', async () => {
    mockGet.mockResolvedValue(fakeRes)
    await usersApi.listUsers(1, 20, '')

    expect(mockGet).toHaveBeenCalledWith('/users', {
      params: { page: 1, page_size: 20, search: undefined },
    })
  })

  it('getUser 应调用 GET /users/:id', async () => {
    mockGet.mockResolvedValue(fakeRes)
    await usersApi.getUser('u-001')

    expect(mockGet).toHaveBeenCalledWith('/users/u-001')
  })

  it('createUser 应调用 POST /users', async () => {
    mockPost.mockResolvedValue(fakeRes)
    const req = { username: 'newuser', password: 'pass123', display_name: '新用户' }
    await usersApi.createUser(req)

    expect(mockPost).toHaveBeenCalledWith('/users', req)
  })

  it('updateUser 应调用 PUT /users/:id', async () => {
    mockPut.mockResolvedValue(fakeRes)
    const req = { display_name: '改名', version: 1 }
    await usersApi.updateUser('u-001', req)

    expect(mockPut).toHaveBeenCalledWith('/users/u-001', req)
  })

  it('deleteUser 应调用 DELETE /users/:id', async () => {
    mockDelete.mockResolvedValue(undefined)
    await usersApi.deleteUser('u-001')

    expect(mockDelete).toHaveBeenCalledWith('/users/u-001')
  })

  it('assignRoles 应调用 POST /users/:id/roles', async () => {
    mockPost.mockResolvedValue(undefined)
    await usersApi.assignRoles('u-001', ['role-1', 'role-2'])

    expect(mockPost).toHaveBeenCalledWith('/users/u-001/roles', { role_ids: ['role-1', 'role-2'] })
  })
})
