-- Create agent_performance_metrics table for trading agent service
-- Tracks agent and strategy performance over time
-- Note: Foreign key to agent_strategies will be added later (migration 040)

CREATE TABLE IF NOT EXISTS agent_performance_metrics (
    metric_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    strategy_id TEXT,  -- NULL for aggregate agent performance, TEXT for now (will become UUID with FK later)
    period_start TIMESTAMPTZ NOT NULL,
    period_end TIMESTAMPTZ NOT NULL,
    total_pnl NUMERIC(20, 2) NOT NULL DEFAULT 0,
    sharpe_ratio NUMERIC(10, 6),
    max_drawdown NUMERIC(10, 6),
    win_rate NUMERIC(5, 4),
    total_trades INTEGER NOT NULL DEFAULT 0,
    winning_trades INTEGER NOT NULL DEFAULT 0,
    losing_trades INTEGER NOT NULL DEFAULT 0,
    avg_trade_pnl NUMERIC(20, 2),
    portfolio_turnover NUMERIC(10, 6),
    total_capital NUMERIC(20, 2),
    final_capital NUMERIC(20, 2),
    return_pct NUMERIC(10, 6),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CHECK (period_end >= period_start)
);

-- Indexes for performance
CREATE INDEX IF NOT EXISTS idx_agent_performance_strategy ON agent_performance_metrics(strategy_id);
CREATE INDEX IF NOT EXISTS idx_agent_performance_period ON agent_performance_metrics(period_start, period_end);
CREATE INDEX IF NOT EXISTS idx_agent_performance_created ON agent_performance_metrics(created_at DESC);

-- Comments
COMMENT ON TABLE agent_performance_metrics IS 'Performance metrics for trading agent and strategies';
COMMENT ON COLUMN agent_performance_metrics.strategy_id IS 'NULL for aggregate agent performance, strategy ID for per-strategy metrics';
COMMENT ON COLUMN agent_performance_metrics.portfolio_turnover IS 'Annualized portfolio turnover rate';
