-- ============================================================================
-- AUDIT SCHEMA - Tabla: trading_audit
-- ============================================================================
-- Auditoría específica de operaciones de trading
-- ============================================================================

CREATE TABLE IF NOT EXISTS audit.trading_audit (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

    -- Actor
    user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
    bot_id UUID,

    -- Acción
    action VARCHAR(50) NOT NULL,
    action_status audit.event_status NOT NULL,

    -- Objeto de la acción
    order_id UUID,
    position_id UUID,
    symbol VARCHAR(20) NOT NULL,

    -- Detalles de la operación
    side VARCHAR(4) NOT NULL, -- 'buy' o 'sell'
    order_type VARCHAR(20),
    quantity DECIMAL(20, 8) NOT NULL,
    price DECIMAL(20, 8),
    executed_price DECIMAL(20, 8),

    -- Resultado
    pnl DECIMAL(20, 8),
    fees DECIMAL(20, 8),

    -- Contexto
    strategy_id UUID,
    signal_id UUID,
    is_paper_trading BOOLEAN DEFAULT FALSE,

    -- Metadata
    execution_time_ms INTEGER,
    broker_response JSONB,
    metadata JSONB DEFAULT '{}',

    -- Timestamps
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Índices
CREATE INDEX idx_trading_audit_user ON audit.trading_audit(user_id);
CREATE INDEX idx_trading_audit_bot ON audit.trading_audit(bot_id) WHERE bot_id IS NOT NULL;
CREATE INDEX idx_trading_audit_symbol ON audit.trading_audit(symbol);
CREATE INDEX idx_trading_audit_action ON audit.trading_audit(action);
CREATE INDEX idx_trading_audit_created ON audit.trading_audit(created_at DESC);
CREATE INDEX idx_trading_audit_order ON audit.trading_audit(order_id) WHERE order_id IS NOT NULL;
CREATE INDEX idx_trading_audit_position ON audit.trading_audit(position_id) WHERE position_id IS NOT NULL;

COMMENT ON TABLE audit.trading_audit IS 'Auditoría detallada de todas las operaciones de trading';
