-- =====================================================
-- FUNCTION: education.update_enrollment_progress()
-- =====================================================
-- Proyecto: OrbiQuant IA (Trading Platform)
-- Módulo: OQI-002 - Education
-- Especificación: ET-EDU-001-database.md
-- Descripción: Actualiza el progreso del enrollment cuando se completa una lección
-- =====================================================

CREATE OR REPLACE FUNCTION education.update_enrollment_progress()
RETURNS TRIGGER AS $$
DECLARE
  v_total_lessons INTEGER;
  v_completed_lessons INTEGER;
  v_progress_percentage DECIMAL(5,2);
BEGIN
  -- Obtener total de lecciones obligatorias del curso
  SELECT COUNT(*)
  INTO v_total_lessons
  FROM education.lessons l
  JOIN education.modules m ON l.module_id = m.id
  JOIN education.courses c ON m.course_id = c.id
  WHERE c.id = (
    SELECT course_id FROM education.enrollments WHERE id = NEW.enrollment_id
  ) AND l.is_mandatory = true;

  -- Obtener lecciones completadas
  SELECT COUNT(*)
  INTO v_completed_lessons
  FROM education.progress
  WHERE enrollment_id = NEW.enrollment_id
    AND is_completed = true;

  -- Calcular porcentaje de progreso
  v_progress_percentage := (v_completed_lessons::DECIMAL / NULLIF(v_total_lessons, 0)::DECIMAL) * 100;

  -- Actualizar enrollment
  UPDATE education.enrollments
  SET
    progress_percentage = COALESCE(v_progress_percentage, 0),
    completed_lessons = v_completed_lessons,
    total_lessons = v_total_lessons,
    updated_at = NOW()
  WHERE id = NEW.enrollment_id;

  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

COMMENT ON FUNCTION education.update_enrollment_progress() IS 'Actualiza progreso del enrollment al completar lecciones';

-- Trigger para actualizar el progreso
CREATE TRIGGER update_enrollment_on_progress
  AFTER INSERT OR UPDATE ON education.progress
  FOR EACH ROW
  WHEN (NEW.is_completed = true)
  EXECUTE FUNCTION education.update_enrollment_progress();
