-- =====================================================
-- INVESTMENT SCHEMA - AGENT EXECUTIONS TABLE
-- =====================================================
-- Description: Tracking de ejecuciones de trading agents
-- Schema: investment
-- Gap: GAP-DDL-005, GAP-007
-- Task: ST-3.3
-- Created: 2026-02-03
-- Updated: 2026-02-03
-- Related: OQI-004 Investment Accounts
-- =====================================================

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
  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 (P&L)
  pnl DECIMAL(20,8),
  pnl_percentage DECIMAL(8,4),
  fees DECIMAL(20,8) DEFAULT 0,

  -- Metricas de ejecucion
  execution_time_ms INTEGER,
  slippage DECIMAL(20,8),

  -- Metricas de riesgo
  risk_score DECIMAL(5,4) CHECK (risk_score IS NULL OR risk_score BETWEEN 0 AND 1),
  position_size_percent DECIMAL(5,2),

  -- Detalles adicionales (JSON)
  trade_details JSONB DEFAULT '{}',
  market_conditions JSONB, -- volatility, trend, liquidity, etc.

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

  -- Metadata ML/AI
  signal_source VARCHAR(50), -- ml_model, llm, manual, scheduled, ensemble
  confidence_score DECIMAL(5,4) CHECK (confidence_score IS NULL OR confidence_score BETWEEN 0 AND 1),
  model_version VARCHAR(50),
  model_id UUID, -- Reference to ML model

  -- Referencias externas
  external_order_id VARCHAR(100),

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

-- =====================================================
-- INDEXES
-- =====================================================

-- Primary lookup indexes
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_status ON investment.agent_executions(status);

-- Time-based indexes
CREATE INDEX idx_agent_exec_date ON investment.agent_executions(executed_at DESC);
CREATE INDEX idx_agent_exec_account_date ON investment.agent_executions(account_id, executed_at DESC);

-- Symbol and P&L indexes (partial for efficiency)
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 DESC NULLS LAST)
  WHERE pnl IS NOT NULL;

-- Performance analysis indexes
CREATE INDEX idx_agent_exec_slippage ON investment.agent_executions(slippage)
  WHERE slippage IS NOT NULL;
CREATE INDEX idx_agent_exec_risk_score ON investment.agent_executions(risk_score)
  WHERE risk_score IS NOT NULL;

-- External reference indexes
CREATE INDEX idx_agent_exec_external_order ON investment.agent_executions(external_order_id)
  WHERE external_order_id IS NOT NULL;
CREATE INDEX idx_agent_exec_model ON investment.agent_executions(model_id)
  WHERE model_id IS NOT NULL;

-- Signal analysis index (composite)
CREATE INDEX idx_agent_exec_signal_confidence ON investment.agent_executions(signal_source, confidence_score DESC NULLS LAST)
  WHERE signal_source IS NOT NULL;

-- =====================================================
-- TRIGGER
-- =====================================================

CREATE TRIGGER trg_agent_executions_updated_at
    BEFORE UPDATE ON investment.agent_executions
    FOR EACH ROW
    EXECUTE FUNCTION public.update_updated_at();

-- =====================================================
-- COMMENTS
-- =====================================================

COMMENT ON TABLE investment.agent_executions IS 'Tracking de ejecuciones de trading agents (Atlas, Orion, Nova)';

-- Agent and execution type
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';

-- Trade details
COMMENT ON COLUMN investment.agent_executions.symbol IS 'Trading pair symbol (e.g., BTCUSDT, EURUSD)';
COMMENT ON COLUMN investment.agent_executions.side IS 'Trade direction: buy or sell';
COMMENT ON COLUMN investment.agent_executions.quantity IS 'Position size in base currency';
COMMENT ON COLUMN investment.agent_executions.entry_price IS 'Entry price of the position';
COMMENT ON COLUMN investment.agent_executions.exit_price IS 'Exit price (null if position still open)';

-- P&L
COMMENT ON COLUMN investment.agent_executions.pnl IS 'Profit/Loss in quote currency';
COMMENT ON COLUMN investment.agent_executions.pnl_percentage IS 'P&L as percentage of position';
COMMENT ON COLUMN investment.agent_executions.fees IS 'Trading fees/commissions paid';

-- Execution metrics
COMMENT ON COLUMN investment.agent_executions.execution_time_ms IS 'Time taken to execute the trade in milliseconds';
COMMENT ON COLUMN investment.agent_executions.slippage IS 'Price slippage between requested and executed price';

-- Risk metrics
COMMENT ON COLUMN investment.agent_executions.risk_score IS 'Risk assessment score at time of execution (0-1)';
COMMENT ON COLUMN investment.agent_executions.position_size_percent IS 'Position size as percentage of portfolio';

-- JSON details
COMMENT ON COLUMN investment.agent_executions.trade_details IS 'JSON with additional trade details (leverage, margin, etc.)';
COMMENT ON COLUMN investment.agent_executions.market_conditions IS 'Market conditions at execution (volatility, trend, liquidity)';

-- Status and errors
COMMENT ON COLUMN investment.agent_executions.status IS 'Execution status: pending, executed, partially_filled, cancelled, failed';
COMMENT ON COLUMN investment.agent_executions.error_code IS 'Standardized error code for failures';
COMMENT ON COLUMN investment.agent_executions.failure_reason IS 'Detailed failure description';
COMMENT ON COLUMN investment.agent_executions.notes IS 'Manual annotations or additional context';

-- ML/AI metadata
COMMENT ON COLUMN investment.agent_executions.signal_source IS 'Signal origin: ml_model, llm, manual, scheduled, ensemble';
COMMENT ON COLUMN investment.agent_executions.confidence_score IS 'ML model confidence score (0-1)';
COMMENT ON COLUMN investment.agent_executions.model_version IS 'Version of the ML model used';
COMMENT ON COLUMN investment.agent_executions.model_id IS 'Reference to ML model that generated the signal';

-- External references
COMMENT ON COLUMN investment.agent_executions.external_order_id IS 'Order ID from external broker/exchange (Binance, MT4, etc.)';

-- Timestamps
COMMENT ON COLUMN investment.agent_executions.executed_at IS 'When the trade was executed';
COMMENT ON COLUMN investment.agent_executions.closed_at IS 'When the position was closed';
COMMENT ON COLUMN investment.agent_executions.created_at IS 'Record creation timestamp';
COMMENT ON COLUMN investment.agent_executions.updated_at IS 'Last modification timestamp';
