import { get, post, del, put } from '@/lib/http/client'
import type { PaginatedData } from '@/types/http'
import type {
  AdminDeviceListParams,
  Device,
  DeviceListParams,
  DeviceStatus,
} from '@/types/device'

export function listDevices(params?: DeviceListParams): Promise<PaginatedData<Device>> {
  return get<PaginatedData<Device>>(
    '/devices',
    params as Record<string, string | number | boolean | undefined>,
  )
}

// 获取所有设备列表（管理员）
export function listAllDevices(params?: AdminDeviceListParams): Promise<PaginatedData<Device>> {
  return get<PaginatedData<Device>>(
    '/admin/devices',
    params as Record<string, string | number | boolean | undefined>,
  )
}

export function getDevice(id: number): Promise<Device> {
  return get<Device>(`/devices/${id}`)
}

export function deleteDevice(id: number): Promise<void> {
  return del<void>(`/devices/${id}`)
}

// 管理员删除设备
export function adminDeleteDevice(id: number): Promise<void> {
  return del<void>(`/admin/devices/${id}`)
}

export function updateDeviceStatus(id: number, status: DeviceStatus): Promise<void> {
  return put<void>(`/devices/${id}/status`, { status })
}

// 管理员更新设备状态
export function adminUpdateDeviceStatus(id: number, status: DeviceStatus): Promise<void> {
  return put<void>(`/admin/devices/${id}/status`, { status })
}

// 信任设备（跳过2FA）
export function trustDevice(id: number, trustDuration?: string): Promise<void> {
  return post<void>(`/devices/${id}/trust`, { trust_duration: trustDuration })
}

// 管理员信任设备
export function adminTrustDevice(id: number, trustDuration?: string): Promise<void> {
  return post<void>(`/admin/devices/${id}/trust`, { trust_duration: trustDuration })
}

// 信任设备（通过device_id字符串）
export function trustDeviceByDeviceId(deviceId: string, trustDuration?: string): Promise<void> {
  return post<void>(`/devices/by-device-id/${encodeURIComponent(deviceId)}/trust`, { trust_duration: trustDuration })
}

// 取消设备信任
export function untrustDevice(id: number): Promise<void> {
  return del<void>(`/devices/${id}/trust`)
}

// 管理员取消设备信任
export function adminUntrustDevice(id: number): Promise<void> {
  return del<void>(`/admin/devices/${id}/trust`)
}

// 获取我的信任设备列表
export function getMyTrustedDevices(): Promise<Device[]> {
  return get<Device[]>('/devices/me/trusted')
}

// 登出所有其他设备
export function logoutOtherDevices(currentDeviceId: number): Promise<void> {
  return post<void>('/devices/me/logout-others', { current_device_id: currentDeviceId })
}
