-- =====================================================
-- INVESTMENT SCHEMA - AGENT EXECUTIONS TABLE
-- =====================================================
-- Description: Tracking de ejecuciones de trading agents
-- Schema: investment
-- Gap: GAP-DDL-005
-- Created: 2026-02-03
-- =====================================================

CREATE TABLE investment.agent_executions (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

  -- Relacion con cuenta PAMM
  account_id UUID NOT NULL REFERENCES investment.accounts(id) ON DELETE CASCADE,

  -- Tipo de agente (Atlas, Orion, Nova)
  agent_type investment.trading_agent NOT NULL,

  -- Tipo de ejecucion
  execution_type VARCHAR(20) NOT NULL CHECK (
    execution_type IN ('trade', 'rebalance', 'distribution', 'stop_loss', 'take_profit', 'hedge')
  ),

  -- Detalles del trade (si aplica)
  symbol VARCHAR(20),
  side VARCHAR(4) CHECK (side IN ('buy', 'sell')),
  quantity DECIMAL(20,8),
  entry_price DECIMAL(20,8),
  exit_price DECIMAL(20,8),

  -- Resultado
  pnl DECIMAL(20,8),
  pnl_percentage DECIMAL(8,4),
  fees DECIMAL(20,8) DEFAULT 0,

  -- Detalles adicionales
  trade_details JSONB DEFAULT '{}',
  market_conditions JSONB, -- volatility, trend, etc.

  -- Estado
  status VARCHAR(20) DEFAULT 'executed' CHECK (
    status IN ('pending', 'executed', 'partially_filled', 'cancelled', 'failed')
  ),
  failure_reason TEXT,

  -- Metadata ML/AI
  signal_source VARCHAR(50), -- ml_model, llm, manual, scheduled
  confidence_score DECIMAL(5,4),
  model_version VARCHAR(50),

  -- Timestamps
  executed_at TIMESTAMPTZ DEFAULT NOW(),
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Indices
CREATE INDEX idx_agent_exec_account ON investment.agent_executions(account_id);
CREATE INDEX idx_agent_exec_type ON investment.agent_executions(agent_type);
CREATE INDEX idx_agent_exec_date ON investment.agent_executions(executed_at DESC);
CREATE INDEX idx_agent_exec_symbol ON investment.agent_executions(symbol)
  WHERE symbol IS NOT NULL;
CREATE INDEX idx_agent_exec_pnl ON investment.agent_executions(pnl)
  WHERE pnl IS NOT NULL;
CREATE INDEX idx_agent_exec_status ON investment.agent_executions(status);

-- Indice compuesto para reportes
CREATE INDEX idx_agent_exec_account_date ON investment.agent_executions(account_id, executed_at DESC);

-- Comentarios
COMMENT ON TABLE investment.agent_executions IS 'Tracking de ejecuciones de trading agents (Atlas, Orion, Nova)';
COMMENT ON COLUMN investment.agent_executions.agent_type IS 'Agente que ejecuto: atlas (conservador), orion (moderado), nova (agresivo)';
COMMENT ON COLUMN investment.agent_executions.execution_type IS 'Tipo: trade, rebalance, distribution, stop_loss, take_profit, hedge';
COMMENT ON COLUMN investment.agent_executions.trade_details IS 'JSON con detalles adicionales del trade';
COMMENT ON COLUMN investment.agent_executions.market_conditions IS 'Condiciones de mercado al momento de ejecucion';
COMMENT ON COLUMN investment.agent_executions.signal_source IS 'Fuente de la senal: ml_model, llm, manual, scheduled';
