/**
 * Admin API Client
 *
 * Provides API functions for admin operations.
 */

import { api } from './apiClient';
import { extractData, extractPaginatedData } from './utils/response';

// Common Types
export interface PaginationParams {
  page?: number;
  page_size?: number;
}

export interface PaginatedResponse<T> {
  items: T[];
  pagination: {
    page: number;
    page_size: number;
    total: number;
    total_pages: number;
  };
}

// Dashboard Types
export interface DashboardStats {
  total_users: number;
  total_projects: number;
  total_tasks: number;
  active_tasks: number;
  pending_tasks: number;
  failed_tasks: number;
  completed_tasks: number;
}

export interface SystemResources {
  cpu_usage: number;
  memory_usage: number;
  disk_usage: number;
  uptime: number;
}

export interface ActivityItem {
  id: string;
  type: string;
  action: string;
  user_id?: string;
  user_name?: string;
  target_id?: string;
  target_type?: string;
  details?: Record<string, unknown>;
  created_at: string;
}

// User Types
export interface AdminUser {
  id: string;
  username: string;
  email?: string;
  is_active: boolean;
  is_superuser: boolean;
  permissions: string[];
  roles: string[];
  avatar_url?: string;
  created_at: number;
  last_login?: number;
}

export interface AdminUserUpdateRequest {
  username?: string;
  email?: string;
  is_active?: boolean;
  is_superuser?: boolean;
  permissions?: string[];
  roles?: string[];
}

// Project Types
export interface AdminProject {
  id: string;
  name: string;
  description?: string;
  type: string;
  status: string;
  user_id: string;
  username: string;
  created_at: number;
  updated_at: number;
  progress: number;
  resolution?: string;
  ratio?: string;
}

// Task Types
export interface AdminTask {
  id: string;
  type: string;
  status: string;
  provider?: string;
  user_id: string;
  project_id?: string;
  project_name?: string;
  username?: string;
  created_at: number;
  updated_at?: number;
  error?: string;
  retry_count: number;
}

export interface TaskStats {
  total: number;
  by_status: Record<string, number>;
  by_type: Record<string, number>;
  by_provider: Record<string, number>;
}

export interface QueueStatus {
  queue_length: number;
  processing_count: number;
  max_workers: number;
  active_workers: number;
}

// Settings Types
export interface SystemSetting {
  key: string;
  value: unknown;
  description?: string;
  updated_at: number;
}

// Dashboard API
export const getDashboardStats = async (): Promise<DashboardStats> => {
  const response = await api.get('/api/v1/admin/dashboard/stats');
  return extractData(response);
};

export const getSystemResources = async (): Promise<{ resources: SystemResources; timestamp: string }> => {
  const response = await api.get('/api/v1/admin/dashboard/system');
  return extractData(response);
};

export const getRecentActivity = async (limit = 20): Promise<{ items: ActivityItem[]; total: number }> => {
  const response = await api.get('/api/v1/admin/dashboard/activity', { params: { limit } });
  return extractData(response);
};

// Users API
export const getUsers = async (params: PaginationParams & { filter?: string; sort?: string }): Promise<PaginatedResponse<AdminUser>> => {
  const response = await api.get('/api/v1/admin/users', { params });
  return extractPaginatedData(response);
};

export const getUser = async (userId: string): Promise<AdminUser> => {
  const response = await api.get(`/api/v1/admin/users/${userId}`);
  return extractData(response);
};

export const updateUser = async (userId: string, data: AdminUserUpdateRequest): Promise<AdminUser> => {
  const response = await api.put(`/api/v1/admin/users/${userId}`, data);
  return extractData(response);
};

export const toggleUserActive = async (userId: string): Promise<{ id: string; is_active: boolean; message: string }> => {
  const response = await api.post(`/api/v1/admin/users/${userId}/toggle-active`);
  return extractData(response);
};

export const deleteUser = async (userId: string): Promise<{ id: string; deleted: boolean; message: string }> => {
  const response = await api.delete(`/api/v1/admin/users/${userId}`);
  return extractData(response);
};

// Projects API
export const getProjects = async (params: PaginationParams & { filter?: string; sort?: string }): Promise<PaginatedResponse<AdminProject>> => {
  const response = await api.get('/api/v1/admin/projects', { params });
  return extractPaginatedData(response);
};

export const getProject = async (projectId: string): Promise<AdminProject> => {
  const response = await api.get(`/api/v1/admin/projects/${projectId}`);
  return extractData(response);
};

export const deleteProject = async (projectId: string): Promise<{ id: string; deleted: boolean; message: string }> => {
  const response = await api.delete(`/api/v1/admin/projects/${projectId}`);
  return extractData(response);
};

// Tasks API
export const getTasks = async (params: PaginationParams & { filter?: string; sort?: string }): Promise<PaginatedResponse<AdminTask>> => {
  const response = await api.get('/api/v1/admin/tasks', { params });
  return extractPaginatedData(response);
};

export const getTaskStats = async (): Promise<TaskStats> => {
  const response = await api.get('/api/v1/admin/tasks/stats');
  return extractData(response);
};

export const getQueueStatus = async (): Promise<QueueStatus> => {
  const response = await api.get('/api/v1/admin/tasks/queue');
  return extractData(response);
};

export const retryTask = async (taskId: string): Promise<{ id: string; status: string; message: string; retry_count: number }> => {
  const response = await api.post(`/api/v1/admin/tasks/${taskId}/retry`);
  return extractData(response);
};

export const deleteTask = async (taskId: string): Promise<{ id: string; deleted: boolean; message: string }> => {
  const response = await api.delete(`/api/v1/admin/tasks/${taskId}`);
  return extractData(response);
};

// Settings API
export const getSettings = async (): Promise<SystemSetting[]> => {
  const response = await api.get('/api/v1/admin/settings');
  return extractData(response);
};

export const updateSetting = async (key: string, value: unknown): Promise<{ key: string; value: unknown; updated_at: number; message: string }> => {
  const response = await api.put(`/api/v1/admin/settings/${key}`, { value });
  return extractData(response);
};
