/**
 * 用户服务
 * 
 * 提供用户管理相关 API 调用
 */

import { get, post, put, del } from '@/lib/http/client'
import type { PaginatedData } from '@/types/http'
import type { Role } from '@/types/auth'
import type {
  User,
  UserStatus,
  CreateUserRequest,
  UserListParams,
  UpdateUserRequest,
  UpdateUserStatusRequest,
  AssignUserRolesRequest,
} from '@/types/user'

interface RawUserListResponse {
  items?: Partial<User>[]
  users?: Partial<User>[]
  total?: number
  page?: number
  page_size?: number
  limit?: number
  offset?: number
}

function normalizeUser(user: Partial<User>): User {
  const numericStatus = typeof user.status === 'string' ? Number(user.status) : user.status
  return {
    id: user.id ?? 0,
    username: user.username ?? '',
    email: user.email ?? '',
    phone: user.phone ?? '',
    nickname: user.nickname ?? '',
    avatar: user.avatar ?? '',
    gender: user.gender ?? 0,
    birthday: user.birthday ?? '',
    region: user.region ?? '',
    bio: user.bio ?? '',
    status: (typeof numericStatus === 'number' && !Number.isNaN(numericStatus) ? numericStatus : 0) as UserStatus,
    last_login_at: user.last_login_at ?? '',
    last_login_ip: user.last_login_ip ?? '',
    created_at: user.created_at ?? '',
    updated_at: user.updated_at ?? '',
  }
}

function normalizeUserListResponse(result?: RawUserListResponse | null): PaginatedData<User> {
  const payload = result ?? {}
  const items = Array.isArray(payload.items) ? payload.items : Array.isArray(payload.users) ? payload.users : []
  const pageSize = payload.page_size ?? payload.limit ?? items.length
  const offset = payload.offset ?? 0
  const page = payload.page ?? (pageSize > 0 ? Math.floor(offset / pageSize) + 1 : 1)

  return {
    items: items.map(normalizeUser),
    total: payload.total ?? items.length,
    page,
    page_size: pageSize,
  }
}

/**
 * 获取用户列表
 * GET /api/v1/users
 */
export async function listUsers(params: UserListParams): Promise<PaginatedData<User>> {
  const result = await get<RawUserListResponse>('/users', params as Record<string, string | number | boolean | undefined>)
  return normalizeUserListResponse(result)
}

/**
 * 获取用户详情
 * GET /api/v1/users/:id
 */
export function getUser(id: number): Promise<User> {
  return get<User>(`/users/${id}`)
}

/**
 * 创建用户
 * POST /api/v1/users
 */
export function createUser(data: CreateUserRequest): Promise<User> {
  return post<User>('/users', data)
}

/**
 * 更新用户信息
 * PUT /api/v1/users/:id
 */
export function updateUser(id: number, data: UpdateUserRequest): Promise<User> {
  return put<User>(`/users/${id}`, data)
}

/**
 * 删除用户
 * DELETE /api/v1/users/:id
 */
export function deleteUser(id: number): Promise<void> {
  return del<void>(`/users/${id}`)
}

/**
 * 更新用户状态
 * PUT /api/v1/users/:id/status
 */
export function updateUserStatus(id: number, data: UpdateUserStatusRequest): Promise<void> {
  return put<void>(`/users/${id}/status`, data)
}

/**
 * 获取用户角色列表
 * GET /api/v1/users/:id/roles
 */
export function getUserRoles(id: number): Promise<Role[]> {
  return get<Role[]>(`/users/${id}/roles`)
}

/**
 * 分配用户角色
 * PUT /api/v1/users/:id/roles
 */
export function assignUserRoles(id: number, data: AssignUserRolesRequest): Promise<void> {
  return put<void>(`/users/${id}/roles`, data)
}

/**
 * 批量更新用户状态
 * PUT /api/v1/users/batch/status
 */
export function batchUpdateStatus(ids: number[], status: UserStatus): Promise<{ count: number }> {
  return put<{ count: number }>('/users/batch/status', { ids, status })
}

/**
 * 批量删除用户
 * DELETE /api/v1/users/batch
 */
export function batchDelete(ids: number[]): Promise<{ count: number }> {
  return del<{ count: number }>('/users/batch', { body: { ids } })
}
