CREATE TABLE IF NOT EXISTS paper_trades (
    id BIGSERIAL PRIMARY KEY,
    recommendation_id BIGINT NOT NULL UNIQUE,
    symbol TEXT NOT NULL,
    side TEXT NOT NULL DEFAULT 'long',
    status TEXT NOT NULL DEFAULT 'open',
    opened_at TEXT NOT NULL,
    closed_at TEXT DEFAULT '',
    entry_price DOUBLE PRECISION NOT NULL,
    exit_price DOUBLE PRECISION DEFAULT 0,
    qty DOUBLE PRECISION NOT NULL,
    notional_usdt DOUBLE PRECISION NOT NULL,
    stop_loss DOUBLE PRECISION DEFAULT 0,
    tp1 DOUBLE PRECISION DEFAULT 0,
    tp2 DOUBLE PRECISION DEFAULT 0,
    trailing_stop DOUBLE PRECISION DEFAULT 0,
    max_price DOUBLE PRECISION DEFAULT 0,
    min_price DOUBLE PRECISION DEFAULT 0,
    current_price DOUBLE PRECISION DEFAULT 0,
    pnl_pct DOUBLE PRECISION DEFAULT 0,
    realized_pnl_pct DOUBLE PRECISION DEFAULT 0,
    realized_pnl_usdt DOUBLE PRECISION DEFAULT 0,
    fee_usdt DOUBLE PRECISION DEFAULT 0,
    exit_reason TEXT DEFAULT '',
    source_status TEXT DEFAULT '',
    source_action TEXT DEFAULT '',
    strategy_version TEXT DEFAULT '',
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_paper_trades_status_updated ON paper_trades(status, updated_at DESC);
CREATE INDEX IF NOT EXISTS idx_paper_trades_symbol_opened ON paper_trades(symbol, opened_at DESC);
CREATE INDEX IF NOT EXISTS idx_paper_trades_recommendation ON paper_trades(recommendation_id);

CREATE TABLE IF NOT EXISTS paper_trade_events (
    id BIGSERIAL PRIMARY KEY,
    trade_id BIGINT NOT NULL,
    recommendation_id BIGINT NOT NULL,
    symbol TEXT NOT NULL,
    event_type TEXT NOT NULL,
    event_time TEXT NOT NULL,
    price DOUBLE PRECISION DEFAULT 0,
    pnl_pct DOUBLE PRECISION DEFAULT 0,
    message TEXT DEFAULT '',
    detail_json TEXT DEFAULT '{}'
);

CREATE INDEX IF NOT EXISTS idx_paper_trade_events_trade_time ON paper_trade_events(trade_id, event_time DESC);
CREATE INDEX IF NOT EXISTS idx_paper_trade_events_symbol_time ON paper_trade_events(symbol, event_time DESC);
