import request, { publicRequest } from './request';

export type DeviceType = 'CONTROLLER' | 'CONTROLLED' | null;

export interface DeviceInfo {
  deviceId: string;
  deviceType: DeviceType;
  online: boolean;
  connectedAt: number | null;
}

export interface DashboardData {
  serverStartTime: number;
  currentTime: number;
  uptimeMs: number;
  totalDevices: number;
  onlineDevices: number;
  offlineDevices: number;
  onlineControllers: number;
  onlineControlled: number;
  pendingConnections: number;
  metrics: {
    totalMessages: number;
    totalOffers: number;
    totalAnswers: number;
    totalRejected: number;
    totalRegistered: number;
    peakSessions: number;
  };
}

export interface PendingConnection {
  fromDeviceId: string;
  toDeviceId: string;
  createdAt: number;
  elapsedMs: number;
}

export interface ServerConfig {
  dedupWindowMs: number;
  requestTimeoutMs: number;
  websocketEndpoint: string;
  serverPort: number;
}

// ==================== 管理员（独立体系） ====================

export interface AdminAccountView {
  adminId: string;
  username: string;
  displayName: string | null;
  status: 'ACTIVE' | 'DISABLED';
  createdAt: number;
  lastLoginAt: number | null;
}

export interface AdminLoginResult {
  token: string;
  tokenType: string;
  expiresIn: number;
  adminId: string;
  username: string;
  displayName: string | null;
}

export function adminLogin(username: string, password: string): Promise<AdminLoginResult> {
  return publicRequest.post('/api/admin/login', { username, password }) as unknown as Promise<AdminLoginResult>;
}

export function getAdmins(): Promise<AdminAccountView[]> {
  return request.get('/api/admin/admins') as unknown as Promise<AdminAccountView[]>;
}

export function createAdmin(username: string, password: string, displayName?: string): Promise<{ success: boolean; admin: AdminAccountView }> {
  return request.post('/api/admin/admins', { username, password, displayName }) as unknown as Promise<{ success: boolean; admin: AdminAccountView }>;
}

export function disableAdmin(adminId: string): Promise<{ success: boolean }> {
  return request.post(`/api/admin/admins/${adminId}/disable`) as unknown as Promise<{ success: boolean }>;
}

export function enableAdmin(adminId: string): Promise<{ success: boolean }> {
  return request.post(`/api/admin/admins/${adminId}/enable`) as unknown as Promise<{ success: boolean }>;
}

export function deleteAdmin(adminId: string): Promise<{ success: boolean }> {
  return request.delete(`/api/admin/admins/${adminId}`) as unknown as Promise<{ success: boolean }>;
}

export function resetAdminPassword(adminId: string, password: string): Promise<{ success: boolean }> {
  return request.post(`/api/admin/admins/${adminId}/reset-password`, { password }) as unknown as Promise<{ success: boolean }>;
}

export function getDashboard(): Promise<DashboardData> {
  return request.get('/api/admin/dashboard') as unknown as Promise<DashboardData>;
}

export function getDevices(type?: string): Promise<DeviceInfo[]> {
  return request.get('/api/admin/devices', { params: type ? { type } : {} }) as unknown as Promise<
    DeviceInfo[]
  >;
}

export function getConnections(): Promise<PendingConnection[]> {
  return request.get('/api/admin/connections') as unknown as Promise<PendingConnection[]>;
}

export function getConfig(): Promise<ServerConfig> {
  return request.get('/api/admin/config') as unknown as Promise<ServerConfig>;
}

export function getHealth(): Promise<{ status: string }> {
  return request.get('/api/admin/health') as unknown as Promise<{ status: string }>;
}

/** 校验管理员令牌有效性（调用 /me 校验）。 */
export function verifyToken(token: string): Promise<unknown> {
  return request.get('/api/admin/me', {
    headers: { Authorization: `Bearer ${token}` },
  }) as Promise<unknown>;
}

// ==================== 用户账号管理 ====================

export type AccountStatus = 'ACTIVE' | 'SUSPENDED' | 'BANNED';

export interface UserAccountView {
  userId: string;
  username: string;
  status: AccountStatus;
  statusReason: string | null;
  statusUntil: number | null;
  totpEnabled: boolean;
  createdAt: number;
  lastLoginAt: number | null;
  activeSessions: number;
}

export interface UserSessionView {
  sessionId: string;
  createdAt: number;
  lastSeenAt: number | null;
  expiresAt: number | null;
  ip: string | null;
  userAgent: string | null;
}

export interface UserQuery {
  keyword?: string;
  status?: string;
}

export function getUsers(query: UserQuery = {}): Promise<UserAccountView[]> {
  return request.get('/api/admin/users', { params: query }) as unknown as Promise<UserAccountView[]>;
}

export function createUser(payload: {
  username: string;
  password: string;
}): Promise<{ success: boolean; message?: string; user?: UserAccountView }> {
  return request.post('/api/admin/users', payload) as unknown as Promise<{
    success: boolean;
    message?: string;
    user?: UserAccountView;
  }>;
}

export function deleteUser(userId: string): Promise<{ success: boolean }> {
  return request.delete(`/api/admin/users/${encodeURIComponent(userId)}`) as unknown as Promise<{
    success: boolean;
  }>;
}

export function resetUserPassword(
  userId: string,
  password: string,
): Promise<{ success: boolean; message?: string }> {
  return request.post(`/api/admin/users/${encodeURIComponent(userId)}/reset-password`, {
    password,
  }) as unknown as Promise<{ success: boolean; message?: string }>;
}

/** 封禁账号，durationSeconds 省略或 <=0 表示永久。 */
export function banUser(
  userId: string,
  reason: string,
  durationSeconds?: number,
): Promise<{ success: boolean }> {
  return request.post(`/api/admin/users/${encodeURIComponent(userId)}/ban`, {
    reason,
    durationSeconds,
  }) as unknown as Promise<{ success: boolean }>;
}

export function unbanUser(userId: string): Promise<{ success: boolean }> {
  return request.post(
    `/api/admin/users/${encodeURIComponent(userId)}/unban`,
  ) as unknown as Promise<{ success: boolean }>;
}

export function kickUser(userId: string, reason?: string): Promise<{ success: boolean }> {
  return request.post(`/api/admin/users/${encodeURIComponent(userId)}/kick`, {
    reason,
  }) as unknown as Promise<{ success: boolean }>;
}

export function getUserSessions(userId: string): Promise<UserSessionView[]> {
  return request.get(
    `/api/admin/users/${encodeURIComponent(userId)}/sessions`,
  ) as unknown as Promise<UserSessionView[]>;
}

export function kickSession(sessionId: string): Promise<{ success: boolean }> {
  return request.post(
    `/api/admin/sessions/${encodeURIComponent(sessionId)}/kick`,
  ) as unknown as Promise<{ success: boolean }>;
}

// ==================== 设备账号管理 ====================

export interface DeviceAccountView {
  deviceUid: string;
  sn: string;
  model: string | null;
  status: AccountStatus;
  statusReason: string | null;
  statusUntil: number | null;
  provisionedAt: number;
  lastOnlineAt: number | null;
  online: boolean;
}

export interface DeviceQuery {
  keyword?: string;
  status?: string;
  online?: boolean;
}

export function getDeviceAccounts(query: DeviceQuery = {}): Promise<DeviceAccountView[]> {
  return request.get('/api/admin/device-accounts', { params: query }) as unknown as Promise<
    DeviceAccountView[]
  >;
}

export function disableDevice(deviceUid: string, reason: string): Promise<{ success: boolean }> {
  return request.post(`/api/admin/device-accounts/${encodeURIComponent(deviceUid)}/disable`, {
    reason,
  }) as unknown as Promise<{ success: boolean }>;
}

export function enableDevice(deviceUid: string): Promise<{ success: boolean }> {
  return request.post(
    `/api/admin/device-accounts/${encodeURIComponent(deviceUid)}/enable`,
  ) as unknown as Promise<{ success: boolean }>;
}

export function kickDevice(deviceUid: string, reason?: string): Promise<{ success: boolean }> {
  return request.post(`/api/admin/device-accounts/${encodeURIComponent(deviceUid)}/kick`, {
    reason,
  }) as unknown as Promise<{ success: boolean }>;
}

export function deleteDevice(deviceUid: string): Promise<{ success: boolean }> {
  return request.delete(
    `/api/admin/device-accounts/${encodeURIComponent(deviceUid)}`,
  ) as unknown as Promise<{ success: boolean }>;
}

// ==================== SN 白名单 ====================

export function getAllowlist(): Promise<{ total: number; sns: string[] }> {
  return request.get('/api/admin/device-allowlist') as unknown as Promise<{
    total: number;
    sns: string[];
  }>;
}

export function importAllowlist(
  sns: string[],
): Promise<{ success: boolean; added: number; total: number }> {
  return request.post('/api/admin/device-allowlist', { sns }) as unknown as Promise<{
    success: boolean;
    added: number;
    total: number;
  }>;
}

export function removeAllowlist(sn: string): Promise<{ success: boolean; total: number }> {
  return request.delete(
    `/api/admin/device-allowlist/${encodeURIComponent(sn)}`,
  ) as unknown as Promise<{ success: boolean; total: number }>;
}

// ==================== 绑定关系 ====================

export type BindingRole = 'OWNER' | 'MEMBER';
export type BindingStatus = 'ACTIVE' | 'REVOKED';

export interface UserBindingView {
  bindingId: string;
  deviceUid: string;
  userId: string;
  role: BindingRole;
  alias: string | null;
  status: BindingStatus;
  online: boolean;
  boundAt: number | null;
}

/** 获取某用户绑定的全部终端设备（含在线状态）。 */
export function getUserBindings(userId: string): Promise<UserBindingView[]> {
  return request.get(
    `/api/admin/users/${encodeURIComponent(userId)}/bindings`,
  ) as unknown as Promise<UserBindingView[]>;
}
