-- ============================================================================
-- AUDIT SCHEMA - Tabla: data_access_logs
-- ============================================================================
-- Log de acceso a datos sensibles (cumplimiento regulatorio)
-- ============================================================================

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

    -- Quién accedió
    accessor_user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
    accessor_role VARCHAR(50) NOT NULL,

    -- A qué datos se accedió
    target_user_id UUID REFERENCES auth.users(id) ON DELETE SET NULL,
    data_category VARCHAR(50) NOT NULL, -- 'pii', 'financial', 'health', 'credentials'
    data_fields TEXT[], -- campos específicos accedidos

    -- Cómo se accedió
    access_type VARCHAR(20) NOT NULL, -- 'view', 'export', 'modify', 'delete'
    access_reason TEXT,

    -- Contexto
    request_id UUID,
    ip_address INET,
    user_agent TEXT,

    -- Compliance
    consent_verified BOOLEAN DEFAULT FALSE,
    legal_basis VARCHAR(100),
    retention_days INTEGER,

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

-- Índices
CREATE INDEX idx_data_access_accessor ON audit.data_access_logs(accessor_user_id);
CREATE INDEX idx_data_access_target ON audit.data_access_logs(target_user_id);
CREATE INDEX idx_data_access_category ON audit.data_access_logs(data_category);
CREATE INDEX idx_data_access_type ON audit.data_access_logs(access_type);
CREATE INDEX idx_data_access_created ON audit.data_access_logs(created_at DESC);

COMMENT ON TABLE audit.data_access_logs IS 'Registro de acceso a datos sensibles para cumplimiento GDPR/CCPA';
COMMENT ON COLUMN audit.data_access_logs.legal_basis IS 'Base legal para el acceso (consentimiento, contrato, obligación legal, etc.)';
