-- Stonks Oracle - Portfolio and account risk configuration
-- Persists risk configuration profiles and tracks risk state snapshots.
-- Requirements: 8.1, 8.2, 8.4

-- ============================================================
-- Risk Configuration Profiles
-- ============================================================

CREATE TABLE risk_configs (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    name VARCHAR(200) NOT NULL DEFAULT 'default',
    trading_mode VARCHAR(20) NOT NULL DEFAULT 'paper',
    config JSONB NOT NULL DEFAULT '{}',
    active BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE UNIQUE INDEX idx_risk_configs_active_name
    ON risk_configs(name) WHERE active = TRUE;

-- ============================================================
-- Symbol-level lockouts (news-shock, cooldown)
-- ============================================================

CREATE TABLE symbol_lockouts (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    ticker VARCHAR(20) NOT NULL,
    lockout_type VARCHAR(50) NOT NULL,
    reason TEXT DEFAULT '',
    expires_at TIMESTAMPTZ NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_symbol_lockouts_ticker ON symbol_lockouts(ticker, expires_at);
CREATE INDEX idx_symbol_lockouts_expiry ON symbol_lockouts(expires_at);

-- ============================================================
-- Daily risk snapshots (for daily loss tracking)
-- ============================================================

CREATE TABLE daily_risk_snapshots (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    account_id VARCHAR(200) NOT NULL,
    snapshot_date DATE NOT NULL DEFAULT CURRENT_DATE,
    portfolio_value NUMERIC DEFAULT 0,
    daily_pnl NUMERIC DEFAULT 0,
    daily_trade_count INTEGER DEFAULT 0,
    positions_by_sector JSONB DEFAULT '{}',
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE(account_id, snapshot_date)
);

CREATE INDEX idx_daily_risk_account ON daily_risk_snapshots(account_id, snapshot_date DESC);
