-- Create agent_orders table for trading agent service
-- Stores orders generated from portfolio allocations

CREATE TABLE IF NOT EXISTS agent_orders (
    order_id TEXT PRIMARY KEY,
    allocation_id TEXT NOT NULL,
    symbol TEXT NOT NULL,
    side TEXT NOT NULL CHECK (side IN ('BUY', 'SELL')),
    quantity NUMERIC(20, 8) NOT NULL CHECK (quantity > 0),
    price NUMERIC(20, 8),
    order_type TEXT NOT NULL CHECK (order_type IN ('MARKET', 'LIMIT', 'STOP', 'STOP_LIMIT')),
    status TEXT NOT NULL CHECK (status IN ('CREATED', 'SUBMITTED', 'PENDING', 'PARTIALLY_FILLED', 'FILLED', 'CANCELLED', 'REJECTED', 'EXPIRED')),
    time_in_force TEXT NOT NULL DEFAULT 'DAY' CHECK (time_in_force IN ('DAY', 'GTC', 'IOC', 'FOK')),
    filled_quantity NUMERIC(20, 8) NOT NULL DEFAULT 0,
    avg_fill_price NUMERIC(20, 8),
    client_order_id TEXT,
    broker_order_id TEXT,
    account_id TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ,
    submitted_at TIMESTAMPTZ,
    filled_at TIMESTAMPTZ,
    metadata JSONB DEFAULT '{}'::jsonb
    -- Note: FK constraint to trading_universes removed for MVP flexibility
    -- Add back in production when allocation table is created
);

-- Indexes for performance
CREATE INDEX IF NOT EXISTS idx_agent_orders_allocation ON agent_orders(allocation_id);
CREATE INDEX IF NOT EXISTS idx_agent_orders_symbol ON agent_orders(symbol);
CREATE INDEX IF NOT EXISTS idx_agent_orders_status ON agent_orders(status);
CREATE INDEX IF NOT EXISTS idx_agent_orders_created ON agent_orders(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_agent_orders_side ON agent_orders(side);

-- Composite index for common queries
CREATE INDEX IF NOT EXISTS idx_agent_orders_allocation_status ON agent_orders(allocation_id, status);
CREATE INDEX IF NOT EXISTS idx_agent_orders_symbol_status ON agent_orders(symbol, status);

-- Comments
COMMENT ON TABLE agent_orders IS 'Orders generated from portfolio allocations by trading agent';
COMMENT ON COLUMN agent_orders.order_id IS 'Unique order identifier';
COMMENT ON COLUMN agent_orders.allocation_id IS 'Reference to portfolio allocation that generated this order';
COMMENT ON COLUMN agent_orders.symbol IS 'Trading symbol (e.g., ES.FUT, NQ.FUT)';
COMMENT ON COLUMN agent_orders.side IS 'Order side: BUY or SELL';
COMMENT ON COLUMN agent_orders.quantity IS 'Order quantity (positive)';
COMMENT ON COLUMN agent_orders.price IS 'Limit price (NULL for market orders)';
COMMENT ON COLUMN agent_orders.order_type IS 'Order type: MARKET, LIMIT, STOP, STOP_LIMIT';
COMMENT ON COLUMN agent_orders.status IS 'Order status in lifecycle';
COMMENT ON COLUMN agent_orders.time_in_force IS 'Time in force policy';
COMMENT ON COLUMN agent_orders.filled_quantity IS 'Quantity that has been filled';
COMMENT ON COLUMN agent_orders.avg_fill_price IS 'Average fill price for executed quantity';
COMMENT ON COLUMN agent_orders.metadata IS 'Additional order metadata (JSON)';
