-- Audit and System Tables

-- System events audit
CREATE TABLE audit.system_events (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    service_name VARCHAR(100) NOT NULL,
    event_type VARCHAR(50) NOT NULL,
    event_data JSONB DEFAULT '{}',
    user_id VARCHAR(255),
    ip_address INET,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Trading events audit
CREATE TABLE audit.trading_events (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    event_type VARCHAR(50) NOT NULL, -- 'order_created', 'order_filled', 'position_opened', etc.
    entity_type VARCHAR(50) NOT NULL, -- 'order', 'position', 'execution'
    entity_id UUID NOT NULL,
    old_values JSONB,
    new_values JSONB,
    changed_by VARCHAR(255),
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Service health monitoring
CREATE TABLE audit.service_health (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    service_name VARCHAR(100) NOT NULL,
    status VARCHAR(20) NOT NULL CHECK (status IN ('healthy', 'unhealthy', 'degraded')),
    version VARCHAR(50),
    uptime_seconds INTEGER,
    memory_usage_mb INTEGER,
    cpu_usage_percent DECIMAL(5,2),
    last_health_check TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    metadata JSONB DEFAULT '{}',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Configuration changes
CREATE TABLE audit.config_changes (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    config_key VARCHAR(255) NOT NULL,
    old_value TEXT,
    new_value TEXT,
    changed_by VARCHAR(255),
    reason TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Create indexes
CREATE INDEX idx_system_events_service_time ON audit.system_events(service_name, created_at);
CREATE INDEX idx_trading_events_type_time ON audit.trading_events(event_type, created_at);
CREATE INDEX idx_trading_events_entity ON audit.trading_events(entity_type, entity_id);
CREATE INDEX idx_service_health_name_time ON audit.service_health(service_name, created_at);
CREATE INDEX idx_config_changes_key_time ON audit.config_changes(config_key, created_at);

-- Grant permissions
GRANT SELECT ON ALL TABLES IN SCHEMA audit TO trading_reader;
