-- Strategy and Risk Management Tables

-- Strategies
CREATE TABLE strategy.strategies (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    name VARCHAR(255) NOT NULL,
    description TEXT,
    version VARCHAR(20) DEFAULT '1.0.0',
    config JSONB DEFAULT '{}',
    parameters JSONB DEFAULT '{}',
    is_active BOOLEAN DEFAULT false,
    is_enabled BOOLEAN DEFAULT true,
    created_by VARCHAR(255),
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Strategy executions/runs
CREATE TABLE strategy.executions (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    strategy_id UUID REFERENCES strategy.strategies(id),
    status VARCHAR(20) DEFAULT 'running' CHECK (status IN ('running', 'stopped', 'error', 'completed')),
    started_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    stopped_at TIMESTAMP WITH TIME ZONE,
    error_message TEXT,
    execution_stats JSONB DEFAULT '{}',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Strategy signals
CREATE TABLE strategy.signals (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    strategy_id UUID REFERENCES strategy.strategies(id),
    symbol_id UUID REFERENCES trading.symbols(id),
    signal_type VARCHAR(20) NOT NULL CHECK (signal_type IN ('buy', 'sell', 'hold')),
    strength DECIMAL(3,2) CHECK (strength >= 0 AND strength <= 1), -- 0.0 to 1.0
    confidence DECIMAL(3,2) CHECK (confidence >= 0 AND confidence <= 1),
    target_price DECIMAL(18,8),
    stop_loss DECIMAL(18,8),
    take_profit DECIMAL(18,8),
    metadata JSONB DEFAULT '{}',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Risk limits
CREATE TABLE risk.limits (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    strategy_id UUID REFERENCES strategy.strategies(id),
    account_id UUID REFERENCES trading.accounts(id),
    limit_type VARCHAR(50) NOT NULL, -- 'max_position_size', 'max_daily_loss', 'max_drawdown', etc.
    limit_value DECIMAL(18,8) NOT NULL,
    current_value DECIMAL(18,8) DEFAULT 0,
    threshold_warning DECIMAL(18,8), -- Warning at X% of limit
    is_active BOOLEAN DEFAULT true,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Risk events/alerts
CREATE TABLE risk.events (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    limit_id UUID REFERENCES risk.limits(id),
    strategy_id UUID,
    event_type VARCHAR(50) NOT NULL, -- 'warning', 'breach', 'resolved'
    severity VARCHAR(20) DEFAULT 'medium' CHECK (severity IN ('low', 'medium', 'high', 'critical')),
    message TEXT NOT NULL,
    current_value DECIMAL(18,8),
    limit_value DECIMAL(18,8),
    metadata JSONB DEFAULT '{}',
    acknowledged BOOLEAN DEFAULT false,
    acknowledged_by VARCHAR(255),
    acknowledged_at TIMESTAMP WITH TIME ZONE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Performance tracking
CREATE TABLE strategy.performance (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    strategy_id UUID REFERENCES strategy.strategies(id),
    date DATE NOT NULL,
    total_return DECIMAL(10,4),
    daily_return DECIMAL(10,4),
    sharpe_ratio DECIMAL(10,4),
    max_drawdown DECIMAL(10,4),
    win_rate DECIMAL(5,4),
    profit_factor DECIMAL(10,4),
    total_trades INTEGER DEFAULT 0,
    winning_trades INTEGER DEFAULT 0,
    losing_trades INTEGER DEFAULT 0,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    UNIQUE(strategy_id, date)
);

-- Create indexes
CREATE INDEX idx_strategies_active ON strategy.strategies(is_active, is_enabled);
CREATE INDEX idx_executions_strategy ON strategy.executions(strategy_id);
CREATE INDEX idx_signals_strategy_time ON strategy.signals(strategy_id, created_at);
CREATE INDEX idx_signals_symbol ON strategy.signals(symbol_id);
CREATE INDEX idx_limits_strategy ON risk.limits(strategy_id);
CREATE INDEX idx_risk_events_severity ON risk.events(severity, created_at);
CREATE INDEX idx_performance_strategy_date ON strategy.performance(strategy_id, date);

-- Grant permissions
GRANT SELECT ON ALL TABLES IN SCHEMA strategy TO trading_reader;
GRANT SELECT ON ALL TABLES IN SCHEMA risk TO trading_reader;
