-- =====================================================
-- FUNCTION: education.auto_complete_enrollment()
-- =====================================================
-- Proyecto: OrbiQuant IA (Trading Platform)
-- Módulo: OQI-002 - Education
-- Especificación: ET-EDU-001-database.md
-- Descripción: Completa automáticamente el enrollment cuando alcanza 100%
-- =====================================================

CREATE OR REPLACE FUNCTION education.auto_complete_enrollment()
RETURNS TRIGGER AS $$
BEGIN
  -- Si el progreso llegó al 100% y está activo, completarlo
  IF NEW.progress_percentage >= 100 AND NEW.status = 'active' THEN
    NEW.status := 'completed';
    NEW.completed_at := NOW();
  END IF;

  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

COMMENT ON FUNCTION education.auto_complete_enrollment() IS 'Completa automáticamente el enrollment al alcanzar 100%';

-- Trigger para auto-completar enrollment
CREATE TRIGGER auto_complete_enrollment_trigger
  BEFORE UPDATE ON education.enrollments
  FOR EACH ROW
  EXECUTE FUNCTION education.auto_complete_enrollment();
