-- Migration 0039: Trade execution schema (VS-12)
-- Creates tables for KIS-integrated trade execution with full audit trail

CREATE TABLE IF NOT EXISTS model_operations.trades (
    id UUID PRIMARY KEY,
    sell_decision_id UUID NOT NULL REFERENCES model_operations.sell_decisions(id),
    kis_order_id VARCHAR(50),
    status VARCHAR(50) NOT NULL DEFAULT 'PENDING',
    quantity INT NOT NULL,
    executed_quantity INT,
    unit_price DECIMAL(15,2),
    total_amount DECIMAL(18,2),
    commission DECIMAL(15,2),
    net_proceeds DECIMAL(18,2),
    error_message TEXT,
    kis_response JSONB,
    execution_timestamp TIMESTAMPTZ,
    settlement_timestamp TIMESTAMPTZ,
    published_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    correlation_id UUID NOT NULL,
    revision INT NOT NULL DEFAULT 1
);

CREATE INDEX IF NOT EXISTS idx_trades_sell_decision_id ON model_operations.trades(sell_decision_id);
CREATE INDEX IF NOT EXISTS idx_trades_status ON model_operations.trades(status);
CREATE INDEX IF NOT EXISTS idx_trades_kis_order_id ON model_operations.trades(kis_order_id);
CREATE INDEX IF NOT EXISTS idx_trades_correlation_id ON model_operations.trades(correlation_id);
CREATE INDEX IF NOT EXISTS idx_trades_published_at ON model_operations.trades(published_at DESC);

CREATE TABLE IF NOT EXISTS model_operations.trade_status_history (
    id UUID PRIMARY KEY,
    trade_id UUID NOT NULL REFERENCES model_operations.trades(id),
    old_status VARCHAR(50),
    new_status VARCHAR(50) NOT NULL,
    transitioned_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    kis_response JSONB,
    error_message TEXT,
    published_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    correlation_id UUID NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_trade_status_history_trade_id ON model_operations.trade_status_history(trade_id);
CREATE INDEX IF NOT EXISTS idx_trade_status_history_new_status ON model_operations.trade_status_history(new_status);
CREATE INDEX IF NOT EXISTS idx_trade_status_history_correlation_id ON model_operations.trade_status_history(correlation_id);
