/**
 * Admin Service
 * API client for admin endpoints - models, predictions, agent performance
 * ARCH-001: ML model calls now go through authenticated Express gateway
 */

import { apiClient } from '@/lib/apiClient';

// ============================================================================
// Types
// ============================================================================

export interface MLModel {
  model_id: string;
  name: string;
  type: 'AMD' | 'ICT' | 'Range' | 'TPSL' | 'Ensemble';
  version: string;
  status: 'active' | 'training' | 'inactive' | 'error';
  accuracy: number;
  precision: number;
  recall: number;
  f1_score: number;
  last_trained: string;
  last_prediction: string;
  total_predictions: number;
  successful_predictions: number;
  metrics: {
    win_rate: number;
    profit_factor: number;
    sharpe_ratio: number;
    max_drawdown: number;
    avg_risk_reward: number;
  };
}

export interface Prediction {
  prediction_id: string;
  model_id: string;
  model_name: string;
  symbol: string;
  direction: 'long' | 'short';
  predicted_price: number;
  actual_price?: number;
  confidence: number;
  created_at: string;
  result?: 'success' | 'failed' | 'pending';
  profit_loss?: number;
  entry_price: number;
  exit_price?: number;
  take_profit: number;
  stop_loss: number;
}

export interface AgentPerformance {
  agent_id: string;
  name: 'Atlas' | 'Orion' | 'Nova';
  description: string;
  status: 'active' | 'paused' | 'stopped';
  total_signals: number;
  successful_signals: number;
  failed_signals: number;
  win_rate: number;
  total_pnl: number;
  total_trades: number;
  avg_profit_per_trade: number;
  best_trade: number;
  worst_trade: number;
  avg_confidence: number;
  sharpe_ratio: number;
  max_drawdown: number;
  last_signal_at: string;
  created_at: string;
  performance_by_symbol: {
    [symbol: string]: {
      trades: number;
      win_rate: number;
      pnl: number;
    };
  };
}

export interface SignalHistory {
  signal_id: string;
  agent_name: string;
  symbol: string;
  direction: 'long' | 'short';
  entry_price: number;
  exit_price?: number;
  stop_loss: number;
  take_profit: number;
  confidence: number;
  status: 'active' | 'completed' | 'stopped';
  result?: 'win' | 'loss' | 'breakeven';
  profit_loss?: number;
  created_at: string;
  closed_at?: string;
}

export interface AdminStats {
  total_models: number;
  active_models: number;
  total_predictions_today: number;
  total_predictions_week: number;
  overall_accuracy: number;
  total_agents: number;
  active_agents: number;
  total_signals_today: number;
  total_pnl_today: number;
  total_pnl_week: number;
  total_pnl_month: number;
  system_health: 'healthy' | 'degraded' | 'down';
}

export interface SystemHealth {
  status: string;
  services: {
    database: { status: string; latency?: number };
    mlEngine: { status: string };
    tradingAgents: { status: string };
    redis?: { status: string };
  };
  system: {
    uptime: number;
    memory: {
      used: number;
      total: number;
      percentage: number;
    };
  };
  timestamp: string;
}

// ============================================================================
// API Functions - ML Models (via proxy)
// ============================================================================

export async function getMLModels(): Promise<MLModel[]> {
  try {
    const response = await apiClient.get('/proxy/ml/models');
    return response.data || [];
  } catch (error) {
    console.error('Error fetching ML models:', error);
    return [];
  }
}

export async function getMLModel(modelId: string): Promise<MLModel | null> {
  try {
    const response = await apiClient.get(`/proxy/ml/models/${modelId}/status`);
    return response.data;
  } catch (error) {
    if ((error as { response?: { status: number } }).response?.status === 404) return null;
    console.error('Error fetching ML model:', error);
    return null;
  }
}

export async function updateMLModelStatus(modelId: string, status: 'active' | 'inactive'): Promise<boolean> {
  try {
    const response = await apiClient.patch(`/proxy/ml/models/${modelId}/status`, { status });
    return response.status === 200;
  } catch (error) {
    console.error('Error updating model status:', error);
    return false;
  }
}

// ============================================================================
// API Functions - Predictions
// ============================================================================

export async function getPredictions(params?: {
  model_id?: string;
  symbol?: string;
  start_date?: string;
  end_date?: string;
  result?: 'success' | 'failed' | 'pending';
  limit?: number;
}): Promise<Prediction[]> {
  try {
    const response = await apiClient.get('/ml/predictions', { params });
    return response.data?.data || [];
  } catch (error) {
    console.error('Error fetching predictions:', error);
    return [];
  }
}

// ============================================================================
// API Functions - Agents
// ============================================================================

export async function getAgents(): Promise<AgentPerformance[]> {
  try {
    const response = await apiClient.get('/agents');
    return response.data?.data || [];
  } catch (error) {
    console.error('Error fetching agents:', error);
    return [];
  }
}

export async function getAgent(agentId: string): Promise<AgentPerformance | null> {
  try {
    const response = await apiClient.get(`/agents/${agentId}`);
    return response.data?.data;
  } catch (error) {
    if ((error as { response?: { status: number } }).response?.status === 404) return null;
    console.error('Error fetching agent:', error);
    return null;
  }
}

export async function updateAgentStatus(agentId: string, status: 'active' | 'paused' | 'stopped'): Promise<boolean> {
  try {
    const response = await apiClient.patch(`/agents/${agentId}/status`, { status });
    return response.status === 200;
  } catch (error) {
    console.error('Error updating agent status:', error);
    return false;
  }
}

// ============================================================================
// API Functions - Signals
// ============================================================================

export async function getSignalHistory(params?: {
  agent_id?: string;
  symbol?: string;
  status?: string;
  limit?: number;
}): Promise<SignalHistory[]> {
  try {
    const response = await apiClient.get('/trading/signals', { params });
    return response.data?.data || [];
  } catch (error) {
    console.error('Error fetching signal history:', error);
    return [];
  }
}

// ============================================================================
// API Functions - Admin Dashboard
// ============================================================================

export async function getAdminDashboard(): Promise<AdminStats | null> {
  try {
    const response = await apiClient.get('/admin/dashboard');
    return response.data?.data;
  } catch (error) {
    console.error('Error fetching admin dashboard:', error);
    return null;
  }
}

export async function getSystemHealth(): Promise<SystemHealth | null> {
  try {
    const response = await apiClient.get('/admin/system/health');
    return response.data?.data;
  } catch (error) {
    console.error('Error fetching system health:', error);
    return null;
  }
}

// ============================================================================
// API Functions - Users Management
// ============================================================================

export interface User {
  id: string;
  email: string;
  role: 'user' | 'premium' | 'admin';
  status: 'active' | 'suspended' | 'banned';
  created_at: string;
  full_name?: string;
  avatar_url?: string;
}

export async function getUsers(params?: {
  page?: number;
  limit?: number;
  status?: string;
  role?: string;
  search?: string;
}): Promise<{ users: User[]; total: number; page: number; totalPages: number }> {
  try {
    const response = await apiClient.get('/admin/users', { params });
    return {
      users: response.data?.data || [],
      total: response.data?.meta?.total || 0,
      page: response.data?.meta?.page || 1,
      totalPages: response.data?.meta?.totalPages || 1,
    };
  } catch (error) {
    console.error('Error fetching users:', error);
    return { users: [], total: 0, page: 1, totalPages: 1 };
  }
}

export async function updateUserStatus(userId: string, status: string, reason?: string): Promise<boolean> {
  try {
    const response = await apiClient.patch(`/admin/users/${userId}/status`, { status, reason });
    return response.status === 200;
  } catch (error) {
    console.error('Error updating user status:', error);
    return false;
  }
}

export async function updateUserRole(userId: string, role: string): Promise<boolean> {
  try {
    const response = await apiClient.patch(`/admin/users/${userId}/role`, { role });
    return response.status === 200;
  } catch (error) {
    console.error('Error updating user role:', error);
    return false;
  }
}

// ============================================================================
// API Functions - Audit Logs
// ============================================================================

export interface AuditLog {
  id: string;
  user_id: string;
  action: string;
  resource: string;
  details: Record<string, unknown>;
  ip_address: string;
  created_at: string;
}

export async function getAuditLogs(params?: {
  page?: number;
  limit?: number;
  userId?: string;
  action?: string;
  startDate?: string;
  endDate?: string;
}): Promise<{ logs: AuditLog[]; total: number }> {
  try {
    const response = await apiClient.get('/admin/audit/logs', { params });
    return {
      logs: response.data?.data || [],
      total: response.data?.meta?.total || 0,
    };
  } catch (error) {
    console.error('Error fetching audit logs:', error);
    return { logs: [], total: 0 };
  }
}
