-- =====================================================
-- FUNCTION: education.update_enrollment_count()
-- =====================================================
-- Proyecto: OrbiQuant IA (Trading Platform)
-- Módulo: OQI-002 - Education
-- Especificación: ET-EDU-001-database.md
-- Descripción: Actualiza el contador de enrollments en courses
-- =====================================================

CREATE OR REPLACE FUNCTION education.update_enrollment_count()
RETURNS TRIGGER AS $$
DECLARE
  v_course_id UUID;
BEGIN
  v_course_id := COALESCE(NEW.course_id, OLD.course_id);

  -- Actualizar contador de enrollments
  UPDATE education.courses
  SET
    total_enrollments = (
      SELECT COUNT(*) FROM education.enrollments WHERE course_id = v_course_id
    ),
    updated_at = NOW()
  WHERE id = v_course_id;

  RETURN COALESCE(NEW, OLD);
END;
$$ LANGUAGE plpgsql;

COMMENT ON FUNCTION education.update_enrollment_count() IS 'Actualiza total_enrollments del curso';

-- Triggers para actualizar contador
CREATE TRIGGER update_enrollment_count_on_insert
  AFTER INSERT ON education.enrollments
  FOR EACH ROW
  EXECUTE FUNCTION education.update_enrollment_count();

CREATE TRIGGER update_enrollment_count_on_delete
  AFTER DELETE ON education.enrollments
  FOR EACH ROW
  EXECUTE FUNCTION education.update_enrollment_count();
