-- =====================================================
-- EMERGES TES - Funciones y Triggers
-- FASE 1: Infraestructura Base
-- =====================================================
-- 
-- Funciones auxiliares y triggers para automatizar
-- tareas comunes del sistema.
-- =====================================================

-- =====================================================
-- FUNCIÓN: Actualizar updated_at automáticamente
-- =====================================================
CREATE OR REPLACE FUNCTION emerges_content.update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- Trigger para content_items
DROP TRIGGER IF EXISTS trg_content_items_updated_at ON emerges_content.content_items;
CREATE TRIGGER trg_content_items_updated_at
    BEFORE UPDATE ON emerges_content.content_items
    FOR EACH ROW
    EXECUTE FUNCTION emerges_content.update_updated_at_column();

-- Trigger para content_relations
DROP TRIGGER IF EXISTS trg_content_relations_updated_at ON emerges_content.content_relations;
CREATE TRIGGER trg_content_relations_updated_at
    BEFORE UPDATE ON emerges_content.content_relations
    FOR EACH ROW
    EXECUTE FUNCTION emerges_content.update_updated_at_column();

-- Trigger para users
DROP TRIGGER IF EXISTS trg_users_updated_at ON emerges_content.users;
CREATE TRIGGER trg_users_updated_at
    BEFORE UPDATE ON emerges_content.users
    FOR EACH ROW
    EXECUTE FUNCTION emerges_content.update_updated_at_column();

-- =====================================================
-- FUNCIÓN: Crear snapshot de versión al actualizar
-- =====================================================
CREATE OR REPLACE FUNCTION emerges_content.create_version_snapshot()
RETURNS TRIGGER AS $$
BEGIN
    -- Si la versión cambió, crear snapshot
    IF NEW.version > OLD.version THEN
        INSERT INTO emerges_content.content_versions (
            content_id,
            version,
            content,
            content_markdown,
            title,
            status,
            validated_by,
            validated_at,
            clinical_source,
            created_by
        ) VALUES (
            NEW.id,
            OLD.version,  -- Versión anterior
            OLD.content,
            OLD.content_markdown,
            OLD.title,
            OLD.status,
            OLD.validated_by,
            OLD.validated_at,
            OLD.clinical_source,
            NEW.updated_by
        );
        
        -- Actualizar latest_version
        NEW.latest_version = NEW.version;
    END IF;
    
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- Trigger para content_items
DROP TRIGGER IF EXISTS trg_content_items_version_snapshot ON emerges_content.content_items;
CREATE TRIGGER trg_content_items_version_snapshot
    BEFORE UPDATE ON emerges_content.content_items
    FOR EACH ROW
    WHEN (NEW.version > OLD.version)
    EXECUTE FUNCTION emerges_content.create_version_snapshot();

-- =====================================================
-- FUNCIÓN: Obtener contenido validado por tipo
-- =====================================================
CREATE OR REPLACE FUNCTION emerges_content.get_validated_content(
    p_type VARCHAR DEFAULT NULL,
    p_level VARCHAR DEFAULT NULL,
    p_category VARCHAR DEFAULT NULL
)
RETURNS TABLE (
    id VARCHAR,
    type VARCHAR,
    level VARCHAR,
    title VARCHAR,
    short_title VARCHAR,
    content JSONB,
    content_markdown TEXT,
    category VARCHAR,
    subcategory VARCHAR,
    priority VARCHAR,
    age_group VARCHAR,
    version INTEGER,
    validated_at TIMESTAMP WITH TIME ZONE,
    clinical_source VARCHAR,
    updated_at TIMESTAMP WITH TIME ZONE
) AS $$
BEGIN
    RETURN QUERY
    SELECT 
        ci.id,
        ci.type,
        ci.level,
        ci.title,
        ci.short_title,
        ci.content,
        ci.content_markdown,
        ci.category,
        ci.subcategory,
        ci.priority,
        ci.age_group,
        ci.version,
        ci.validated_at,
        ci.clinical_source,
        ci.updated_at
    FROM emerges_content.content_items ci
    WHERE ci.status = 'validated'
        AND (p_type IS NULL OR ci.type = p_type)
        AND (p_level IS NULL OR ci.level = p_level)
        AND (p_category IS NULL OR ci.category = p_category)
    ORDER BY ci.updated_at DESC;
END;
$$ LANGUAGE plpgsql;

-- =====================================================
-- FUNCIÓN: Verificar actualizaciones disponibles
-- =====================================================
CREATE OR REPLACE FUNCTION emerges_content.check_updates(
    p_last_sync TIMESTAMP WITH TIME ZONE
)
RETURNS TABLE (
    content_id VARCHAR,
    type VARCHAR,
    version INTEGER,
    updated_at TIMESTAMP WITH TIME ZONE
) AS $$
BEGIN
    RETURN QUERY
    SELECT 
        ci.id,
        ci.type,
        ci.version,
        ci.updated_at
    FROM emerges_content.content_items ci
    WHERE ci.status = 'validated'
        AND ci.updated_at > p_last_sync
    ORDER BY ci.updated_at DESC;
END;
$$ LANGUAGE plpgsql;

