import type { AuthUser, UserRole, UserStatus } from '../auth'

async function readJson<T>(response: Response): Promise<T> {
  if (!response.ok) {
    const payload = await response.json().catch(() => null) as { detail?: string } | null
    throw new Error(payload?.detail || `请求失败：${response.status}`)
  }
  return response.json() as Promise<T>
}

export async function fetchUsers(): Promise<AuthUser[]> {
  const response = await readJson<{ items: AuthUser[] }>(await fetch('/api/admin/users'))
  return response.items
}

export async function createUser(payload: {
  username: string
  password: string
  display_name: string
  role: UserRole
}): Promise<AuthUser> {
  return readJson(await fetch('/api/admin/users', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  }))
}

export async function updateUser(
  userId: number,
  payload: {
    display_name?: string
    role?: UserRole
    status?: UserStatus
    password?: string
  },
): Promise<AuthUser> {
  return readJson(await fetch(`/api/admin/users/${userId}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  }))
}

export async function removeUser(userId: number): Promise<void> {
  const response = await fetch(`/api/admin/users/${userId}`, { method: 'DELETE' })
  if (!response.ok) {
    const payload = await response.json().catch(() => null) as { detail?: string } | null
    throw new Error(payload?.detail || `删除失败：${response.status}`)
  }
}
