-- ============================================================================
-- AUDIT SCHEMA - Tabla: system_events
-- ============================================================================
-- Eventos del sistema (jobs, tareas programadas, errores)
-- ============================================================================

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

    -- Categorización
    event_type VARCHAR(50) NOT NULL,
    severity audit.event_severity NOT NULL DEFAULT 'info',

    -- Origen
    service_name VARCHAR(100) NOT NULL,
    component VARCHAR(100),
    environment VARCHAR(20) NOT NULL DEFAULT 'production',
    hostname VARCHAR(255),

    -- Detalles
    event_name VARCHAR(255) NOT NULL,
    message TEXT NOT NULL,
    stack_trace TEXT,

    -- Contexto
    correlation_id UUID,
    job_id VARCHAR(100),
    duration_ms INTEGER,

    -- Metadata
    metadata JSONB DEFAULT '{}',
    tags TEXT[],

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

-- Índices
CREATE INDEX idx_system_events_service ON audit.system_events(service_name);
CREATE INDEX idx_system_events_type ON audit.system_events(event_type);
CREATE INDEX idx_system_events_severity ON audit.system_events(severity);
CREATE INDEX idx_system_events_created ON audit.system_events(created_at DESC);
CREATE INDEX idx_system_events_correlation ON audit.system_events(correlation_id) WHERE correlation_id IS NOT NULL;
CREATE INDEX idx_system_events_job ON audit.system_events(job_id) WHERE job_id IS NOT NULL;
CREATE INDEX idx_system_events_tags ON audit.system_events USING GIN (tags);

COMMENT ON TABLE audit.system_events IS 'Eventos del sistema para monitoreo de infraestructura y jobs';
