#!/usr/bin/env node
/**
 * Debug-Script zum Prüfen, ob Übungen für eine Lektion vorhanden sind
 * Verwendung: node debug-lesson-exercises.js [lessonId]
 */

import { sequelize } from './backend/utils/sequelize.js';
import VocabCourseLesson from './backend/models/community/vocab_course_lesson.js';
import VocabGrammarExercise from './backend/models/community/vocab_grammar_exercise.js';

const lessonId = process.argv[2] ? parseInt(process.argv[2]) : 1;

async function debugLesson() {
  try {
    await sequelize.authenticate();
    console.log('✅ Datenbankverbindung erfolgreich\n');

    // Lade Lektion mit Übungen (wie im Backend)
    const lesson = await VocabCourseLesson.findByPk(lessonId, {
      include: [
        {
          model: require('./backend/models/community/vocab_course.js').default,
          as: 'course'
        },
        {
          model: VocabGrammarExercise,
          as: 'grammarExercises',
          include: [
            {
              model: require('./backend/models/community/vocab_grammar_exercise_type.js').default,
              as: 'exerciseType'
            }
          ],
          required: false,
          separate: true,
          order: [['exerciseNumber', 'ASC']]
        }
      ]
    });

    if (!lesson) {
      console.log(`❌ Lektion ${lessonId} nicht gefunden`);
      return;
    }

    console.log(`📚 Lektion: ${lesson.title} (ID: ${lesson.id})`);
    console.log(`   Kurs: ${lesson.course?.title || 'N/A'}`);
    console.log(`   Übungen (via Include): ${lesson.grammarExercises ? lesson.grammarExercises.length : 0}\n`);

    // Prüfe direkt in der Datenbank
    const directExercises = await VocabGrammarExercise.findAll({
      where: { lessonId: lesson.id },
      order: [['exerciseNumber', 'ASC']]
    });

    console.log(`📊 Direkte Abfrage: ${directExercises.length} Übung(en) gefunden`);
    directExercises.forEach((ex, idx) => {
      console.log(`   ${idx + 1}. ${ex.title} (ID: ${ex.id}, Typ: ${ex.exerciseTypeId})`);
    });

    // Plain object
    const plain = lesson.get({ plain: true });
    console.log(`\n📦 Plain Object:`);
    console.log(`   grammarExercises: ${plain.grammarExercises ? plain.grammarExercises.length : 'undefined'}`);
    if (plain.grammarExercises && plain.grammarExercises.length > 0) {
      plain.grammarExercises.forEach((ex, idx) => {
        console.log(`   ${idx + 1}. ${ex.title} (ID: ${ex.id})`);
      });
    }

  } catch (error) {
    console.error('❌ Fehler:', error);
  } finally {
    await sequelize.close();
  }
}

debugLesson();
