-- =====================================================
-- FUNCTION: education.update_updated_at_column()
-- =====================================================
-- Proyecto: OrbiQuant IA (Trading Platform)
-- Módulo: OQI-002 - Education
-- Especificación: ET-EDU-001-database.md
-- Descripción: Actualiza automáticamente el campo updated_at
-- =====================================================

CREATE OR REPLACE FUNCTION education.update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = NOW();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

COMMENT ON FUNCTION education.update_updated_at_column() IS 'Actualiza automáticamente updated_at en cada UPDATE';

-- Aplicar trigger a todas las tablas relevantes
CREATE TRIGGER update_categories_updated_at
  BEFORE UPDATE ON education.categories
  FOR EACH ROW
  EXECUTE FUNCTION education.update_updated_at_column();

CREATE TRIGGER update_courses_updated_at
  BEFORE UPDATE ON education.courses
  FOR EACH ROW
  EXECUTE FUNCTION education.update_updated_at_column();

CREATE TRIGGER update_modules_updated_at
  BEFORE UPDATE ON education.modules
  FOR EACH ROW
  EXECUTE FUNCTION education.update_updated_at_column();

CREATE TRIGGER update_lessons_updated_at
  BEFORE UPDATE ON education.lessons
  FOR EACH ROW
  EXECUTE FUNCTION education.update_updated_at_column();

CREATE TRIGGER update_enrollments_updated_at
  BEFORE UPDATE ON education.enrollments
  FOR EACH ROW
  EXECUTE FUNCTION education.update_updated_at_column();

CREATE TRIGGER update_progress_updated_at
  BEFORE UPDATE ON education.progress
  FOR EACH ROW
  EXECUTE FUNCTION education.update_updated_at_column();

CREATE TRIGGER update_quizzes_updated_at
  BEFORE UPDATE ON education.quizzes
  FOR EACH ROW
  EXECUTE FUNCTION education.update_updated_at_column();

CREATE TRIGGER update_quiz_questions_updated_at
  BEFORE UPDATE ON education.quiz_questions
  FOR EACH ROW
  EXECUTE FUNCTION education.update_updated_at_column();

CREATE TRIGGER update_user_gamification_profile_updated_at
  BEFORE UPDATE ON education.user_gamification_profile
  FOR EACH ROW
  EXECUTE FUNCTION education.update_updated_at_column();

CREATE TRIGGER update_course_reviews_updated_at
  BEFORE UPDATE ON education.course_reviews
  FOR EACH ROW
  EXECUTE FUNCTION education.update_updated_at_column();
