/**
 * Investment Module Types
 * Type definitions for PAMM accounts, trading agents, and profit distribution
 * Aligned with investment schema DDL (00-enums.sql)
 */

// ============================================================================
// Investment Enums (Alineado con investment.* DDL)
// ============================================================================

// Alineado con investment.trading_agent (DDL)
export type TradingAgent = 'atlas' | 'orion' | 'nova';

// Alineado con investment.risk_profile (DDL)
export type RiskProfile = 'conservative' | 'moderate' | 'aggressive';

// Alineado con investment.account_status (DDL)
export type InvestmentAccountStatus =
  | 'pending_kyc'
  | 'active'
  | 'suspended'
  | 'closed';

// Alineado con investment.distribution_frequency (DDL)
export type DistributionFrequency = 'monthly' | 'quarterly';

// Alineado con investment.transaction_type (DDL)
export type InvestmentTransactionType =
  | 'deposit'
  | 'withdrawal'
  | 'distribution';

// Alineado con investment.transaction_status (DDL)
export type InvestmentTransactionStatus =
  | 'pending'
  | 'processing'
  | 'completed'
  | 'failed'
  | 'cancelled';

// ============================================================================
// Agent Configuration
// ============================================================================

export interface AgentConfig {
  id: TradingAgent;
  name: string;
  displayName: string;
  riskProfile: RiskProfile;
  monthlyTargetMin: number;
  monthlyTargetMax: number;
  maxDrawdown: number;
  minCapital: number;
  maxRiskPerTrade: number;
  maxPositions: number;
  strategies: string[];
  instruments: string[];
  description: string;
  isActive: boolean;
}

// Pre-defined agent configurations
export const AGENT_CONFIGS: Record<TradingAgent, AgentConfig> = {
  atlas: {
    id: 'atlas',
    name: 'Atlas',
    displayName: 'Atlas - Conservador',
    riskProfile: 'conservative',
    monthlyTargetMin: 3,
    monthlyTargetMax: 5,
    maxDrawdown: 5,
    minCapital: 200,
    maxRiskPerTrade: 1,
    maxPositions: 1,
    strategies: ['Mean Reversion', 'Grid Trading'],
    instruments: ['XAUUSD'],
    description: 'Estrategia conservadora enfocada en preservar capital',
    isActive: true,
  },
  orion: {
    id: 'orion',
    name: 'Orion',
    displayName: 'Orion - Moderado',
    riskProfile: 'moderate',
    monthlyTargetMin: 5,
    monthlyTargetMax: 10,
    maxDrawdown: 10,
    minCapital: 500,
    maxRiskPerTrade: 1.5,
    maxPositions: 2,
    strategies: ['Trend Following', 'Breakouts'],
    instruments: ['EURUSD', 'GBPUSD'],
    description: 'Equilibrio entre crecimiento y control de riesgo',
    isActive: true,
  },
  nova: {
    id: 'nova',
    name: 'Nova',
    displayName: 'Nova - Agresivo',
    riskProfile: 'aggressive',
    monthlyTargetMin: 10,
    monthlyTargetMax: 15,
    maxDrawdown: 20,
    minCapital: 1000,
    maxRiskPerTrade: 2,
    maxPositions: 3,
    strategies: ['Momentum', 'Scalping'],
    instruments: ['XAUUSD', 'EURUSD', 'GBPUSD', 'USDJPY'],
    description: 'Maximiza retornos con mayor tolerancia al riesgo',
    isActive: true,
  },
};

// ============================================================================
// Investment Account Types
// ============================================================================

export interface InvestmentAccount {
  id: string;
  tenantId: string;
  userId: string;
  agent: TradingAgent;
  status: InvestmentAccountStatus;
  balance: number;
  equity: number;
  availableBalance: number;
  pendingDeposits: number;
  pendingWithdrawals: number;
  totalDeposited: number;
  totalWithdrawn: number;
  totalProfit: number;
  totalDistributed: number;
  distributionFrequency: DistributionFrequency;
  lastDistributionAt?: string;
  nextDistributionAt?: string;
  createdAt: string;
  updatedAt: string;
}

export interface InvestmentAccountWithStats extends InvestmentAccount {
  performance: AccountPerformance;
  recentTransactions: InvestmentTransaction[];
}

// ============================================================================
// Transaction Types
// ============================================================================

export interface InvestmentTransaction {
  id: string;
  tenantId: string;
  accountId: string;
  type: InvestmentTransactionType;
  status: InvestmentTransactionStatus;
  amount: number;
  fee: number;
  netAmount: number;
  balanceBefore: number;
  balanceAfter: number;
  description: string;
  referenceId?: string;
  externalId?: string;
  processedAt?: string;
  failureReason?: string;
  metadata?: Record<string, unknown>;
  createdAt: string;
  updatedAt: string;
}

// ============================================================================
// Profit Distribution Types
// ============================================================================

export interface ProfitDistribution {
  id: string;
  tenantId: string;
  accountId: string;
  periodStart: string;
  periodEnd: string;
  grossProfit: number;
  platformFee: number;
  platformFeePercentage: number;
  netProfit: number;
  reinvestmentAmount: number;
  reinvestmentPercentage: number;
  distributedAmount: number;
  distributedPercentage: number;
  status: 'pending' | 'processing' | 'completed' | 'failed';
  processedAt?: string;
  transactionId?: string;
  createdAt: string;
}

export interface DistributionConfig {
  platformFeePercentage: number; // e.g., 20%
  reinvestmentPercentage: number; // e.g., 80%
  distributionPercentage: number; // e.g., 20%
  minDistributionAmount: number;
}

// ============================================================================
// Performance Types
// ============================================================================

export interface AccountPerformance {
  totalReturn: number;
  totalReturnPercentage: number;
  monthlyReturn: number;
  monthlyReturnPercentage: number;
  weeklyReturn: number;
  weeklyReturnPercentage: number;
  dailyReturn: number;
  dailyReturnPercentage: number;
  maxDrawdown: number;
  maxDrawdownPercentage: number;
  sharpeRatio?: number;
  winRate?: number;
  totalTrades?: number;
  profitableTrades?: number;
  lastUpdatedAt: string;
}

export interface AgentPerformance {
  agent: TradingAgent;
  period: 'day' | 'week' | 'month' | 'quarter' | 'year' | 'all';
  returnPercentage: number;
  maxDrawdown: number;
  sharpeRatio: number;
  winRate: number;
  totalTrades: number;
  totalInvestors: number;
  totalAum: number; // Assets Under Management
}

// ============================================================================
// Allocation Types
// ============================================================================

export interface Allocation {
  id: string;
  tenantId: string;
  userId: string;
  agent: TradingAgent;
  percentage: number;
  amount: number;
  isActive: boolean;
  createdAt: string;
  updatedAt: string;
}

export interface AllocationRequest {
  allocations: Array<{
    agent: TradingAgent;
    percentage: number;
  }>;
}

// ============================================================================
// Risk Questionnaire Types
// ============================================================================

export interface RiskQuestionnaireQuestion {
  id: string;
  question: string;
  options: Array<{
    value: string;
    label: string;
    score: number;
  }>;
}

export interface RiskQuestionnaireResult {
  userId: string;
  answers: Record<string, string>;
  totalScore: number;
  recommendedProfile: RiskProfile;
  recommendedAgent: TradingAgent;
  completedAt: string;
}

// ============================================================================
// API Request/Response Types
// ============================================================================

export interface CreateInvestmentAccountRequest {
  agent: TradingAgent;
  initialDeposit: number;
  distributionFrequency?: DistributionFrequency;
}

export interface DepositRequest {
  accountId: string;
  amount: number;
  paymentMethodId?: string;
}

export interface WithdrawalRequest {
  accountId: string;
  amount: number;
  destinationWalletId?: string;
}

export interface InvestmentAccountResponse {
  account: InvestmentAccountWithStats;
  config: AgentConfig;
}
