-- Exchanges reference table
CREATE TABLE exchanges (
    id SMALLINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
    name TEXT NOT NULL UNIQUE
);

-- Instruments reference table
CREATE TABLE instruments (
    id INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
    exchange_id SMALLINT NOT NULL REFERENCES exchanges(id),
    name_exchange TEXT NOT NULL,
    base_asset TEXT NOT NULL,
    quote_asset TEXT NOT NULL,
    kind TEXT NOT NULL,
    UNIQUE (exchange_id, name_exchange)
);

CREATE INDEX idx_instruments_exchange ON instruments(exchange_id);

-- Market trades (one row per trade)
-- Uses DOUBLE PRECISION matching barter's f64 for PublicTrade.price/amount
CREATE TABLE market_trades (
    id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
    instrument_id INTEGER NOT NULL REFERENCES instruments(id),
    time_exchange TIMESTAMPTZ NOT NULL,
    time_received TIMESTAMPTZ NOT NULL,
    trade_id TEXT NOT NULL,
    price DOUBLE PRECISION NOT NULL,
    amount DOUBLE PRECISION NOT NULL,
    side TEXT NOT NULL
);

CREATE INDEX idx_market_trades_instrument_time ON market_trades(instrument_id, time_exchange);

-- Market order book L1 snapshots
-- Uses NUMERIC matching barter's rust_decimal::Decimal for Level fields
CREATE TABLE market_order_book_l1 (
    id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
    instrument_id INTEGER NOT NULL REFERENCES instruments(id),
    time_exchange TIMESTAMPTZ NOT NULL,
    time_received TIMESTAMPTZ NOT NULL,
    best_bid_price NUMERIC,
    best_bid_amount NUMERIC,
    best_ask_price NUMERIC,
    best_ask_amount NUMERIC
);

CREATE INDEX idx_market_order_book_l1_instrument_time ON market_order_book_l1(instrument_id, time_exchange);

-- Paper run status enum
CREATE TYPE paper_run_status AS ENUM ('queued', 'running', 'complete', 'failed', 'cancelled');

-- Paper runs queue
CREATE TABLE paper_runs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    status paper_run_status NOT NULL DEFAULT 'queued',
    config JSONB NOT NULL,
    starts_at TIMESTAMPTZ NOT NULL,
    finishes_at TIMESTAMPTZ NOT NULL,
    risk_free_return NUMERIC NOT NULL DEFAULT 0.05,
    result_summary JSONB,
    error_message TEXT,
    worker_id TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    started_at TIMESTAMPTZ,
    completed_at TIMESTAMPTZ
);

CREATE INDEX idx_paper_runs_status ON paper_runs(status, created_at);
