-- Core trading tables

-- Symbols and instruments
CREATE TABLE trading.symbols (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    symbol VARCHAR(20) NOT NULL UNIQUE,
    name VARCHAR(255),
    exchange VARCHAR(50),
    asset_type VARCHAR(20) DEFAULT 'equity',
    sector VARCHAR(100),
    is_active BOOLEAN DEFAULT true,
    metadata JSONB DEFAULT '{}',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Orders
CREATE TABLE trading.orders (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    symbol_id UUID REFERENCES trading.symbols(id),
    strategy_id UUID,
    order_type VARCHAR(20) NOT NULL, -- 'market', 'limit', 'stop', etc.
    side VARCHAR(10) NOT NULL CHECK (side IN ('buy', 'sell')),
    quantity DECIMAL(18,8) NOT NULL CHECK (quantity > 0),
    price DECIMAL(18,8),
    stop_price DECIMAL(18,8),
    status VARCHAR(20) DEFAULT 'pending' CHECK (status IN ('pending', 'submitted', 'filled', 'cancelled', 'rejected')),
    broker_order_id VARCHAR(100),
    filled_quantity DECIMAL(18,8) DEFAULT 0,
    avg_fill_price DECIMAL(18,8),
    commission DECIMAL(18,8) DEFAULT 0,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    CONSTRAINT valid_prices CHECK (
        (order_type = 'market') OR 
        (order_type = 'limit' AND price IS NOT NULL) OR
        (order_type = 'stop' AND stop_price IS NOT NULL)
    )
);

-- Positions
CREATE TABLE trading.positions (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    symbol_id UUID REFERENCES trading.symbols(id),
    strategy_id UUID,
    quantity DECIMAL(18,8) NOT NULL,
    avg_cost DECIMAL(18,8) NOT NULL,
    market_value DECIMAL(18,8),
    unrealized_pnl DECIMAL(18,8),
    realized_pnl DECIMAL(18,8) DEFAULT 0,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    UNIQUE(symbol_id, strategy_id)
);

-- Executions/Fills
CREATE TABLE trading.executions (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    order_id UUID REFERENCES trading.orders(id),
    symbol_id UUID REFERENCES trading.symbols(id),
    side VARCHAR(10) NOT NULL CHECK (side IN ('buy', 'sell')),
    quantity DECIMAL(18,8) NOT NULL,
    price DECIMAL(18,8) NOT NULL,
    commission DECIMAL(18,8) DEFAULT 0,
    broker_execution_id VARCHAR(100),
    executed_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Accounts/Portfolios
CREATE TABLE trading.accounts (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    name VARCHAR(255) NOT NULL,
    account_type VARCHAR(50) DEFAULT 'paper', -- 'paper', 'live'
    broker VARCHAR(50),
    cash_balance DECIMAL(18,2) DEFAULT 0,
    buying_power DECIMAL(18,2) DEFAULT 0,
    total_value DECIMAL(18,2) DEFAULT 0,
    is_active BOOLEAN DEFAULT true,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Create indexes for performance
CREATE INDEX idx_orders_symbol_created ON trading.orders(symbol_id, created_at);
CREATE INDEX idx_orders_status ON trading.orders(status);
CREATE INDEX idx_orders_strategy ON trading.orders(strategy_id);
CREATE INDEX idx_positions_strategy ON trading.positions(strategy_id);
CREATE INDEX idx_executions_order ON trading.executions(order_id);
CREATE INDEX idx_executions_symbol_time ON trading.executions(symbol_id, executed_at);

-- Grant permissions to reader
GRANT SELECT ON ALL TABLES IN SCHEMA trading TO trading_reader;
