/**
 * Admin API - User Management
 */

import { api as client } from '../apiClient';

export interface UserProject {
  id: string;
  name: string;
  type: string;
  status: string;
  description?: string;
  createdAt: string;
  updatedAt?: string;
}

export interface UserActivity {
  id: string;
  action: string;
  resourceType: string;
  resourceId?: string;
  description?: string;
  metadata?: Record<string, any>;
  type?: string;
  details?: Record<string, any>;
  createdAt: string;
}

export interface AdminUser {
  id: string;
  username: string;
  email?: string;
  isActive: boolean;
  isSuperuser: boolean;
  permissions: string[];
  roles: string[];
  createdAt: string | number;
  lastLogin?: string | number;
  projects?: UserProject[];
  activityHistory?: UserActivity[];
}

export interface PaginationParams {
  page?: number;
  pageSize?: number;
}

export interface PaginationMeta {
  page: number;
  pageSize: number;
  total: number;
  totalPages: number;
}

export interface PaginatedResponse<T> {
  items: T[];
  page: number;
  pageSize: number;
  total: number;
  totalPages: number;
}

export interface UserListParams extends PaginationParams {
  search?: string;
  isActive?: boolean;
  status?: string;
  sortBy?: string;
  sortOrder?: string;
}

export const listUsers = async (params: UserListParams): Promise<PaginatedResponse<AdminUser>> => {
  const response = await client.get('/api/admin/users', { params });
  // Response is wrapped in ResponseModel, data property contains { items, pagination }
  const { items, pagination } = response.data.data;
  return {
    items,
    ...pagination,
  };
};

export const getUser = async (id: string): Promise<AdminUser> => {
  const response = await client.get(`/api/admin/users/${id}`);
  // Response is wrapped in ResponseModel
  return response.data.data;
};

export const createUser = async (data: Omit<AdminUser, 'id' | 'createdAt'>): Promise<AdminUser> => {
  const response = await client.post('/api/admin/users', data);
  return response.data;
};

export const updateUser = async (id: string, data: Partial<AdminUser>): Promise<AdminUser> => {
  const response = await client.patch(`/api/admin/users/${id}`, data);
  return response.data;
};

export const toggleUserActive = async (id: string): Promise<AdminUser> => {
  const response = await client.post(`/api/admin/users/${id}/toggle`);
  return response.data;
};

export const deleteUser = async (id: string): Promise<void> => {
  await client.delete(`/api/admin/users/${id}`);
};

/**
 * Admin API - API Keys
 */

export interface AdminApiKey {
  id: string;
  name: string;
  provider: string;
  userId: string;
  username?: string;
  email?: string;
  maskedKey?: string;
  isActive?: boolean;
  createdAt: string;
  expiresAt?: string;
  usageCount?: number;
  lastUsedAt?: number;
}

export const listApiKeys = async (params: { page?: number; pageSize?: number; userId?: string; provider?: string }): Promise<PaginatedResponse<AdminApiKey>> => {
  const response = await client.get('/api/admin/api-keys', { params });
  const { items, pagination } = response.data.data;
  return {
    items,
    ...pagination,
  };
};

export const revokeApiKey = async (id: string): Promise<void> => {
  await client.delete(`/api/admin/api-keys/${id}`);
};

export interface ApiKeyUsageRecord {
  taskId?: string;
  taskType?: string;
  model?: string;
  createdAt?: string;
}

export interface ApiKeyUsage {
  records: ApiKeyUsageRecord[];
  usageCount?: number;
}

export const getApiKeyUsage = async (id: string): Promise<ApiKeyUsage> => {
  const response = await client.get(`/api/admin/api-keys/${id}/usage`);
  return response.data;
};

/**
 * Admin API - Storage
 */

export interface StorageStats {
  totalFiles: number;
  totalSize: number;
  totalCapacity?: number;
  usedSpace?: number;
  usagePercent?: number;
  fileCount?: number;
}

export interface StorageFile {
  id: string;
  key: string;
  path?: string;
  size: number;
  createdAt: string;
  userId: string;
  username?: string;
  projectName?: string;
  projectId?: string;
}

export const getStorageStats = async (): Promise<StorageStats> => {
  const response = await client.get('/api/admin/storage/stats');
  return response.data;
};

export const listStorageFiles = async (params: { page?: number; pageSize?: number; userId?: string; projectId?: string }): Promise<PaginatedResponse<StorageFile>> => {
  const response = await client.get('/api/admin/storage/files', { params });
  const { items, pagination } = response.data.data;
  return {
    items,
    ...pagination,
  };
};

export const getStorageUserRanking = async (params: { limit?: number }): Promise<any[]> => {
  const response = await client.get('/api/admin/storage/ranking', { params });
  return response.data;
};

export const cleanupOrphanFiles = async (): Promise<{ deleted: number }> => {
  const response = await client.post('/api/admin/storage/cleanup');
  return response.data;
};

/**
 * Admin API - Models
 */

export interface ModelInfo {
  id: string;
  name: string;
  provider: string;
  enabled: boolean;
  is_default: boolean;
}

export const listModels = async (): Promise<ModelInfo[]> => {
  const response = await client.get('/api/admin/models');
  return response.data;
};

export const toggleModel = async (id: string): Promise<ModelInfo> => {
  const response = await client.post(`/api/admin/models/${id}/toggle`);
  return response.data;
};

export const setDefaultModel = async (id: string): Promise<ModelInfo> => {
  const response = await client.post(`/api/admin/models/${id}/set-default`);
  return response.data;
};

export const testModel = async (id: string): Promise<{ success: boolean; message: string; status?: string; latency?: number; latencyMs?: number }> => {
  const response = await client.post(`/api/admin/models/${id}/test`);
  return response.data;
};

export const listProviders = async (): Promise<any[]> => {
  const response = await client.get('/config/providers');
  // Response is wrapped in ResponseModel, data contains the array directly
  return response.data.data;
};

export const toggleProvider = async (id: string): Promise<any> => {
  const response = await client.post(`/api/admin/providers/${id}/toggle`);
  return response.data;
};

export const deleteProvider = async (id: string): Promise<void> => {
  await client.delete(`/api/admin/providers/${id}`);
};

/**
 * Admin API - Audit Logs
 */

export interface AuditLog {
  id: string;
  userId: string;
  username?: string;
  action: string;
  resource: string;
  resourceType?: string;
  resourceId?: string;
  ipAddress?: string;
  userAgent?: string;
  details: any;
  createdAt: string;
}

export const listAuditLogs = async (params: { page?: number; pageSize?: number; userId?: string; action?: string }): Promise<PaginatedResponse<AuditLog>> => {
  const response = await client.get('/api/admin/audit-logs', { params });
  const { items, pagination } = response.data.data;
  return {
    items,
    ...pagination,
  };
};

export const getAuditLog = async (id: string): Promise<AuditLog> => {
  const response = await client.get(`/api/admin/audit-logs/${id}`);
  return response.data;
};

export const exportAuditLogs = async (params: { format?: string }): Promise<Blob> => {
  const response = await client.get('/api/admin/audit-logs/export', { params, responseType: 'blob' });
  return response.data;
};
