-- ============================================================================
-- AUDIT SCHEMA - Tabla: audit_logs
-- ============================================================================
-- Tabla principal de auditoría general
-- ============================================================================

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

    -- Información del evento
    event_type audit.audit_event_type NOT NULL,
    event_status audit.event_status NOT NULL DEFAULT 'success',
    severity audit.event_severity NOT NULL DEFAULT 'info',

    -- Quién realizó la acción
    user_id UUID REFERENCES auth.users(id) ON DELETE SET NULL,
    session_id UUID,
    ip_address INET,
    user_agent TEXT,

    -- Qué se modificó
    resource_type audit.resource_type NOT NULL,
    resource_id UUID,
    resource_name VARCHAR(255),

    -- Detalles del cambio
    action VARCHAR(100) NOT NULL,
    description TEXT,
    old_values JSONB,
    new_values JSONB,
    metadata JSONB DEFAULT '{}',

    -- Contexto
    request_id UUID,
    correlation_id UUID,
    service_name VARCHAR(50),

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

-- Índices para consultas frecuentes
CREATE INDEX idx_audit_logs_user_id ON audit.audit_logs(user_id);
CREATE INDEX idx_audit_logs_resource ON audit.audit_logs(resource_type, resource_id);
CREATE INDEX idx_audit_logs_event_type ON audit.audit_logs(event_type);
CREATE INDEX idx_audit_logs_created_at ON audit.audit_logs(created_at DESC);
CREATE INDEX idx_audit_logs_severity ON audit.audit_logs(severity) WHERE severity IN ('error', 'critical');
CREATE INDEX idx_audit_logs_correlation ON audit.audit_logs(correlation_id) WHERE correlation_id IS NOT NULL;

-- Índice GIN para búsqueda en JSONB
CREATE INDEX idx_audit_logs_metadata ON audit.audit_logs USING GIN (metadata);

COMMENT ON TABLE audit.audit_logs IS 'Log general de auditoría para todas las acciones del sistema';
COMMENT ON COLUMN audit.audit_logs.correlation_id IS 'ID para correlacionar eventos relacionados en una misma operación';
