-- ============================================================================
-- AUDIT SCHEMA - Tabla: compliance_logs
-- ============================================================================
-- Log de eventos de cumplimiento regulatorio
-- ============================================================================

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

    -- Regulación
    regulation VARCHAR(50) NOT NULL, -- 'GDPR', 'CCPA', 'SOX', 'PCI-DSS', 'MiFID'
    requirement VARCHAR(100) NOT NULL,

    -- Evento
    event_type VARCHAR(50) NOT NULL,
    event_description TEXT NOT NULL,

    -- Actor
    user_id UUID REFERENCES auth.users(id) ON DELETE SET NULL,
    system_initiated BOOLEAN DEFAULT FALSE,

    -- Estado
    compliance_status VARCHAR(20) NOT NULL, -- 'compliant', 'non_compliant', 'remediation'
    risk_level VARCHAR(20), -- 'low', 'medium', 'high', 'critical'

    -- Detalles
    evidence JSONB,
    remediation_required BOOLEAN DEFAULT FALSE,
    remediation_deadline TIMESTAMPTZ,
    remediation_notes TEXT,

    -- Revisión
    reviewed_by UUID REFERENCES auth.users(id),
    reviewed_at TIMESTAMPTZ,

    -- Metadata
    metadata JSONB DEFAULT '{}',

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

-- Índices
CREATE INDEX idx_compliance_regulation ON audit.compliance_logs(regulation);
CREATE INDEX idx_compliance_status ON audit.compliance_logs(compliance_status);
CREATE INDEX idx_compliance_risk ON audit.compliance_logs(risk_level);
CREATE INDEX idx_compliance_created ON audit.compliance_logs(created_at DESC);
CREATE INDEX idx_compliance_remediation ON audit.compliance_logs(remediation_required)
    WHERE remediation_required = TRUE;

COMMENT ON TABLE audit.compliance_logs IS 'Registro de cumplimiento regulatorio para auditorías';
