const { Op } = require("sequelize");
const {
  TrainingCourse,
  TrainingModule,
  TrainingLesson,
  TrainingQuiz,
  TrainingCourseEnrollment,
  TrainingModuleProgress,
  TrainingLessonProgress,
  Users,
} = require("../models");
const { randomUUID } = require("crypto");
const { logActivity, getIpAddress, getUserAgent } = require("../utils/activityLogger");
const {
  saveTrainingVideo,
  deleteTrainingVideoFile,
} = require("../utils/uploadTrainingVideo");

const DEFAULT_PASS_SCORE = 75;

// ============================================
// USER ENDPOINTS
// ============================================

/**
 * GET /api/training-courses
 * Get all active courses with user enrollment status
 */
const getAllCourses = async (req, res) => {
  try {
    console.log('🔍 getAllCourses called by user:', req.user?.id);
    
    const courses = await TrainingCourse.findAll({
      where: { isActive: true },
      order: [["order", "ASC"]],
      include: [
        {
          model: TrainingModule,
          include: [
            {
              model: TrainingLesson,
              order: [["order", "ASC"]],
            },
            {
              model: TrainingQuiz,
              order: [["order", "ASC"]],
            },
          ],
          order: [["order", "ASC"]],
        },
      ],
    });

    console.log('📚 Found courses:', courses.length);

    // Get user enrollments
    const enrollments = await TrainingCourseEnrollment.findAll({
      where: { UserId: req.user.id },
    });

    const enrollmentMap = {};
    enrollments.forEach((e) => {
      enrollmentMap[e.TrainingCourseId] = {
        status: e.status,
        overallScore: e.overallScore,
        certificateId: e.certificateId,
        completedAt: e.completedAt,
        enrolledAt: e.enrolledAt,
      };
    });

    const response = courses.map((course) => ({
      id: course.id,
      title: course.title,
      description: course.description,
      category: course.category,
      standard: course.standard,
      level: course.level,
      passScore: course.passScore ?? DEFAULT_PASS_SCORE,
      thumbnailUrl: course.thumbnailUrl,
      estimatedDuration: course.estimatedDuration,
      moduleCount: course.TrainingModules?.length || 0,
      lessonCount: course.TrainingModules?.reduce(
        (sum, m) => sum + (m.TrainingLessons?.length || 0),
        0
      ),
      quizCount: course.TrainingModules?.reduce(
        (sum, m) => sum + (m.TrainingQuizzes?.length || 0),
        0
      ),
      enrollment: enrollmentMap[course.id] || null,
    }));

    console.log('✅ Sending response with', response.length, 'courses');
    res.json(response);
  } catch (err) {
    console.error("Error fetching courses:", err);
    res.status(500).json({ message: "Failed to fetch courses" });
  }
};

/**
 * GET /api/training-courses/:courseId
 * Get detailed course with modules, lessons, quizzes, and user progress
 */
const getCourseDetail = async (req, res) => {
  const { courseId } = req.params;
  try {
    const course = await TrainingCourse.findByPk(courseId, {
      include: [
        {
          model: TrainingModule,
          include: [
            {
              model: TrainingLesson,
              order: [["order", "ASC"]],
            },
            {
              model: TrainingQuiz,
              attributes: ["id", "question", "options", "order"], // Don't send correctAnswer
              order: [["order", "ASC"]],
            },
          ],
          order: [["order", "ASC"]],
        },
      ],
    });

    if (!course) {
      return res.status(404).json({ message: "Course not found" });
    }

    // Get or create enrollment
    let [enrollment] = await TrainingCourseEnrollment.findOrCreate({
      where: { UserId: req.user.id, TrainingCourseId: courseId },
      defaults: {
        UserId: req.user.id,
        TrainingCourseId: courseId,
        status: "not-started",
      },
    });

    // Get module progress
    const moduleProgress = await TrainingModuleProgress.findAll({
      where: { UserId: req.user.id, TrainingCourseEnrollmentId: enrollment.id },
    });

    const moduleProgressMap = {};
    moduleProgress.forEach((mp) => {
      moduleProgressMap[mp.TrainingModuleId] = {
        status: mp.status,
        quizScore: mp.quizScore,
        completedAt: mp.completedAt,
      };
    });

    // Get lesson progress
    const lessonIds = course.TrainingModules.flatMap((m) =>
      m.TrainingLessons.map((l) => l.id)
    );
    const lessonProgress = await TrainingLessonProgress.findAll({
      where: { UserId: req.user.id, TrainingLessonId: lessonIds },
    });

    const lessonProgressMap = {};
    lessonProgress.forEach((lp) => {
      lessonProgressMap[lp.TrainingLessonId] = {
        watchProgressPercent: lp.watchProgressPercent,
        completed: lp.completed,
        lastWatchedAt: lp.lastWatchedAt,
      };
    });

    const response = {
      id: course.id,
      title: course.title,
      description: course.description,
      category: course.category,
      standard: course.standard,
      level: course.level,
      passScore: course.passScore ?? DEFAULT_PASS_SCORE,
      thumbnailUrl: course.thumbnailUrl,
      estimatedDuration: course.estimatedDuration,
      enrollment: {
        status: enrollment.status,
        overallScore: enrollment.overallScore,
        certificateId: enrollment.certificateId,
        completedAt: enrollment.completedAt,
        enrolledAt: enrollment.enrolledAt,
      },
      modules: course.TrainingModules.map((module) => ({
        id: module.id,
        title: module.title,
        description: module.description,
        order: module.order,
        progress: moduleProgressMap[module.id] || { status: "not-started" },
        lessons: module.TrainingLessons.map((lesson) => ({
          id: lesson.id,
          title: lesson.title,
          description: lesson.description,
          videoFileName: lesson.videoFileName,
          youtubeId: lesson.youtubeId,
          duration: lesson.duration,
          watchUnlockPercent: lesson.watchUnlockPercent,
          order: lesson.order,
          progress: lessonProgressMap[lesson.id] || {
            watchProgressPercent: 0,
            completed: false,
          },
        })),
        quizzes: module.TrainingQuizzes.map((quiz) => ({
          id: quiz.id,
          question: quiz.question,
          options: quiz.options,
          order: quiz.order,
        })),
      })),
    };

    res.json(response);
  } catch (err) {
    console.error("Error fetching course detail:", err);
    res.status(500).json({ message: "Failed to fetch course detail" });
  }
};

/**
 * POST /api/training-courses/:courseId/modules/:moduleId/lessons/:lessonId/progress
 * Update lesson watch progress
 */
const updateLessonProgress = async (req, res) => {
  const { courseId, moduleId, lessonId } = req.params;
  const { watchProgressPercent } = req.body;

  try {
    const moduleOk = await TrainingModule.findOne({
      where: { id: moduleId, TrainingCourseId: courseId },
    });
    if (!moduleOk) {
      return res.status(404).json({ message: "Module not found" });
    }

    const lesson = await TrainingLesson.findOne({
      where: { id: lessonId, TrainingModuleId: moduleId },
    });

    if (!lesson) {
      return res.status(404).json({ message: "Lesson not found" });
    }

    const unlock = Number(lesson.watchUnlockPercent) || 80;
    const pct = Math.min(100, Math.max(0, Number(watchProgressPercent) || 0));
    const completed = pct >= unlock;

    const [progress, created] = await TrainingLessonProgress.findOrCreate({
      where: { UserId: req.user.id, TrainingLessonId: lessonId },
      defaults: {
        UserId: req.user.id,
        TrainingLessonId: lessonId,
        watchProgressPercent: pct,
        completed,
        lastWatchedAt: new Date(),
      },
    });

    // findOrCreate returns plain objects (autoPlainSequelize); use Model.update not instance.update
    let outPct = pct;
    let outCompleted = completed;
    if (!created) {
      outPct = Math.max(Number(progress.watchProgressPercent) || 0, pct);
      outCompleted = outPct >= unlock;
      await TrainingLessonProgress.update(
        {
          watchProgressPercent: outPct,
          completed: outCompleted,
          lastWatchedAt: new Date(),
        },
        {
          where: { UserId: req.user.id, TrainingLessonId: lessonId },
        },
      );
    }

    res.json({
      watchProgressPercent: outPct,
      completed: outCompleted,
    });
  } catch (err) {
    console.error("Error updating lesson progress:", err);
    res.status(500).json({ message: "Failed to update progress" });
  }
};

/**
 * POST /api/training-courses/:courseId/modules/:moduleId/complete
 * Submit module quiz and mark as complete
 */
/**
 * POST /api/training-courses/:courseId/modules/:moduleId/quizzes/:quizId/check
 * Validate one answer (for step-by-step quiz UI; final score still from completeModule)
 */
const checkQuizAnswer = async (req, res) => {
  const { courseId, moduleId, quizId } = req.params;
  const answerIndex = Number(req.body?.answerIndex);

  try {
    const module = await TrainingModule.findOne({
      where: { id: moduleId, TrainingCourseId: courseId },
    });
    if (!module) {
      return res.status(404).json({ message: "Module not found" });
    }

    const quiz = await TrainingQuiz.findOne({
      where: { id: quizId, TrainingModuleId: moduleId },
    });
    if (!quiz) {
      return res.status(404).json({ message: "Question not found" });
    }

    const correct = answerIndex === quiz.correctAnswer;
    res.json({
      correct,
      correctIndex: quiz.correctAnswer,
      explanation: quiz.explanation || "",
    });
  } catch (err) {
    console.error("Error checking quiz answer:", err);
    res.status(500).json({ message: "Failed to check answer" });
  }
};

const completeModule = async (req, res) => {
  const { courseId, moduleId } = req.params;
  const { answers } = req.body; // Array of answer indices

  try {
    const courseRow = await TrainingCourse.findByPk(courseId);
    const passScore = courseRow?.passScore ?? DEFAULT_PASS_SCORE;

    // Get module with quizzes and lessons
    const module = await TrainingModule.findOne({
      where: { id: moduleId, TrainingCourseId: courseId },
      include: [
        { model: TrainingQuiz, order: [["order", "ASC"]] },
        { model: TrainingLesson },
      ],
    });

    if (!module) {
      return res.status(404).json({ message: "Module not found" });
    }

    // Check if all lessons are watched
    const lessonIds = module.TrainingLessons.map((l) => l.id);
    const lessonProgress = await TrainingLessonProgress.findAll({
      where: { UserId: req.user.id, TrainingLessonId: lessonIds },
    });

    const allLessonsWatched = lessonIds.every((lid) =>
      lessonProgress.some((lp) => lp.TrainingLessonId === lid && lp.completed)
    );

    if (!allLessonsWatched) {
      return res.status(400).json({
        message: "Please watch all lessons before taking the quiz",
      });
    }

    // Get or create course enrollment
    const [enrollment] = await TrainingCourseEnrollment.findOrCreate({
      where: { UserId: req.user.id, TrainingCourseId: courseId },
      defaults: {
        UserId: req.user.id,
        TrainingCourseId: courseId,
        status: "in-progress",
      },
    });

    const ans = Array.isArray(answers) ? answers : [];

    // Calculate quiz score
    let correct = 0;
    module.TrainingQuizzes.forEach((quiz, index) => {
      if (ans[index] === quiz.correctAnswer) {
        correct++;
      }
    });

    const quizScore =
      module.TrainingQuizzes.length > 0
        ? Math.round((correct / module.TrainingQuizzes.length) * 100)
        : 100;

    const passed = quizScore >= passScore;
    const status = passed ? "completed" : "failed";

    // Update or create module progress
    await TrainingModuleProgress.findOrCreate({
      where: {
        UserId: req.user.id,
        TrainingModuleId: moduleId,
      },
      defaults: {
        UserId: req.user.id,
        TrainingModuleId: moduleId,
        TrainingCourseEnrollmentId: enrollment.id,
        status,
        quizScore,
        quizAnswers: ans,
        completedAt: passed ? new Date() : null,
      },
    });

    await TrainingModuleProgress.update(
      {
        status,
        quizScore,
        quizAnswers: ans,
        completedAt: passed ? new Date() : null,
        TrainingCourseEnrollmentId: enrollment.id,
      },
      {
        where: { UserId: req.user.id, TrainingModuleId: moduleId },
      },
    );

    // Check if all modules in course are completed
    const allModules = await TrainingModule.findAll({
      where: { TrainingCourseId: courseId },
    });

    const allModuleProgress = await TrainingModuleProgress.findAll({
      where: {
        UserId: req.user.id,
        TrainingCourseEnrollmentId: enrollment.id,
      },
    });

    const allModulesCompleted =
      allModules.length === allModuleProgress.filter((mp) => mp.status === "completed").length;

    if (allModulesCompleted && passed) {
      // Calculate overall score
      const overallScore = Math.round(
        allModuleProgress.reduce((sum, mp) => sum + (mp.quizScore || 0), 0) /
          allModuleProgress.length
      );

      const certificateId = `CERT-${randomUUID().replace(/-/g, "").slice(0, 8).toUpperCase()}`;

      await TrainingCourseEnrollment.update(
        {
          status: "completed",
          overallScore,
          certificateId,
          completedAt: new Date(),
        },
        { where: { id: enrollment.id, UserId: req.user.id } },
      );

      await logActivity({
        userId: req.user.id,
        companyId: req.user.companyId,
        action: "create",
        entityType: "Training Course",
        entityId: courseId,
        description: `Completed training course: ${module.TrainingCourse?.title || "Course"}`,
        metadata: { overallScore, certificateId },
        ipAddress: getIpAddress(req),
        userAgent: getUserAgent(req),
      });

      return res.json({
        status: "completed",
        quizScore,
        courseCompleted: true,
        certificateId,
        overallScore,
      });
    }

    res.json({
      status,
      quizScore,
      courseCompleted: false,
      passed,
    });
  } catch (err) {
    console.error("Error completing module:", err);
    res.status(500).json({ message: "Failed to complete module" });
  }
};

/**
 * POST /api/training-courses/:courseId/reset-progress
 * Clear lesson/module progress and enrollment completion for this user (retake course)
 */
const resetCourseProgress = async (req, res) => {
  const { courseId } = req.params;
  try {
    const enrollment = await TrainingCourseEnrollment.findOne({
      where: { UserId: req.user.id, TrainingCourseId: courseId },
    });
    if (!enrollment) {
      return res.status(404).json({ message: "Enrollment not found" });
    }

    const modules = await TrainingModule.findAll({
      where: { TrainingCourseId: courseId },
      include: [{ model: TrainingLesson }],
    });
    const lessonIds = modules.flatMap((m) =>
      (m.TrainingLessons || []).map((l) => l.id)
    );
    const moduleIds = modules.map((m) => m.id);

    if (lessonIds.length) {
      await TrainingLessonProgress.destroy({
        where: { UserId: req.user.id, TrainingLessonId: lessonIds },
      });
    }
    if (moduleIds.length) {
      await TrainingModuleProgress.destroy({
        where: {
          UserId: req.user.id,
          TrainingModuleId: moduleIds,
          TrainingCourseEnrollmentId: enrollment.id,
        },
      });
    }

    await TrainingCourseEnrollment.update(
      {
        status: "not-started",
        overallScore: null,
        certificateId: null,
        completedAt: null,
      },
      { where: { id: enrollment.id, UserId: req.user.id } },
    );

    res.json({ message: "Progress reset" });
  } catch (err) {
    console.error("Error resetting course progress:", err);
    res.status(500).json({ message: "Failed to reset progress" });
  }
};

const getMyCertificates = async (req, res) => {
  try {
    const enrollments = await TrainingCourseEnrollment.findAll({
      where: { UserId: req.user.id, status: "completed" },
      include: [{ model: TrainingCourse }],
      order: [["completedAt", "DESC"]],
    });

    const certificates = enrollments.map((e) => ({
      certificateId: e.certificateId,
      completedAt: e.completedAt,
      overallScore: e.overallScore,
      courseTitle: e.TrainingCourse?.title,
      category: e.TrainingCourse?.category,
      standard: e.TrainingCourse?.standard,
      level: e.TrainingCourse?.level,
      courseId: e.TrainingCourseId,
    }));

    res.json(certificates);
  } catch (err) {
    console.error("Error fetching certificates:", err);
    res.status(500).json({ message: "Failed to fetch certificates" });
  }
};

// ============================================
// ADMIN ENDPOINTS
// ============================================

/**
 * POST /api/training-courses/admin/course
 * Create a new course
 */
const createCourse = async (req, res) => {
  try {
    const {
      title,
      description,
      category,
      standard,
      level,
      estimatedDuration,
      order,
      passScore,
      modules, // Array of modules with lessons and quizzes
    } = req.body;

    if (!title) {
      return res.status(400).json({
        message: "Title is required",
      });
    }

    const moduleList = Array.isArray(modules) ? modules : [];

    // Create course
    const course = await TrainingCourse.create({
      title,
      description,
      category,
      standard,
      level: level || "foundation",
      estimatedDuration,
      order: order || 0,
      passScore:
        passScore !== undefined && passScore !== null
          ? Math.min(100, Math.max(0, Number(passScore)))
          : DEFAULT_PASS_SCORE,
      isActive: true,
    });

    // Create modules, lessons, and quizzes
    for (const moduleData of moduleList) {
      const module = await TrainingModule.create({
        TrainingCourseId: course.id,
        title: moduleData.title,
        description: moduleData.description,
        order: moduleData.order || 0,
      });

      // Create lessons
      if (moduleData.lessons && Array.isArray(moduleData.lessons)) {
        for (const lessonData of moduleData.lessons) {
          await TrainingLesson.create({
            TrainingModuleId: module.id,
            title: lessonData.title,
            description: lessonData.description,
            videoFileName: lessonData.videoFileName,
            youtubeId: lessonData.youtubeId,
            duration: lessonData.duration,
            watchUnlockPercent: lessonData.watchUnlockPercent || 80,
            order: lessonData.order || 0,
          });
        }
      }

      // Create quizzes
      if (moduleData.quizzes && Array.isArray(moduleData.quizzes)) {
        for (const quizData of moduleData.quizzes) {
          await TrainingQuiz.create({
            TrainingModuleId: module.id,
            question: quizData.question,
            options: quizData.options,
            correctAnswer: quizData.correctAnswer,
            explanation: quizData.explanation,
            order: quizData.order || 0,
          });
        }
      }
    }

    // Fetch complete course with relations
    const completeCourse = await TrainingCourse.findByPk(course.id, {
      include: [
        {
          model: TrainingModule,
          include: [TrainingLesson, TrainingQuiz],
        },
      ],
    });

    res.status(201).json(completeCourse);
  } catch (err) {
    console.error("Error creating course:", err);
    res.status(500).json({ message: err.message || "Failed to create course" });
  }
};

/**
 * POST /api/training-courses/admin/course/:courseId/module/:moduleId/lesson/:lessonId/upload
 * Upload video for a lesson
 */
const uploadLessonVideo = async (req, res) => {
  const { courseId, moduleId, lessonId } = req.params;

  try {
    // Note: autoPlainSequelize patches findByPk/findOne to return plain objects (no .update()).
    // Use Model.update({ where }) instead of instance.update().
    const moduleRow = await TrainingModule.findOne({
      where: { id: moduleId, TrainingCourseId: courseId },
    });
    if (!moduleRow) {
      return res.status(404).json({ message: "Module not found" });
    }

    const lesson = await TrainingLesson.findOne({
      where: { id: lessonId, TrainingModuleId: moduleId },
    });

    if (!lesson) {
      return res.status(404).json({ message: "Lesson not found" });
    }

    if (!req.files || !req.files.video) {
      return res.status(400).json({ message: "No video file provided" });
    }

    if (lesson.videoFileName) {
      try {
        deleteTrainingVideoFile(lesson.videoFileName);
      } catch (e) {
        console.warn("Could not delete old video file:", e?.message);
      }
    }

    const videoFileName = await saveTrainingVideo(req.files.video);
    await TrainingLesson.update(
      { videoFileName },
      { where: { id: lessonId, TrainingModuleId: moduleId } },
    );

    res.json({ videoFileName, message: "Video uploaded successfully" });
  } catch (err) {
    console.error("Error uploading video:", err);
    res.status(500).json({ message: "Failed to upload video" });
  }
};

/**
 * GET /api/training-courses/admin/courses
 * Get all courses (admin view)
 */
const getAllCoursesAdmin = async (req, res) => {
  try {
    const courses = await TrainingCourse.findAll({
      order: [["order", "ASC"]],
      include: [
        {
          model: TrainingModule,
          include: [TrainingLesson, TrainingQuiz],
        },
      ],
    });

    res.json(courses);
  } catch (err) {
    console.error("Error fetching courses (admin):", err);
    res.status(500).json({ message: "Failed to fetch courses" });
  }
};

/**
 * DELETE /api/training-courses/admin/course/:courseId
 * Delete a course (explicit child deletes so MySQL FK order never blocks CASCADE)
 */
const deleteCourse = async (req, res) => {
  const { courseId } = req.params;
  const transaction = await TrainingCourse.sequelize.transaction();

  try {
    const course = await TrainingCourse.findByPk(courseId, {
      include: [{ model: TrainingModule, include: [TrainingLesson] }],
      transaction,
    });

    if (!course) {
      await transaction.rollback();
      return res.status(404).json({ message: "Course not found" });
    }

    const modules = course.TrainingModules || [];
    const moduleIds = modules.map((m) => m.id);
    const lessonIds = modules.flatMap((m) =>
      (m.TrainingLessons || []).map((l) => l.id),
    );

    for (const mod of modules) {
      for (const lesson of mod.TrainingLessons || []) {
        if (lesson.videoFileName) {
          try {
            deleteTrainingVideoFile(lesson.videoFileName);
          } catch (fileErr) {
            console.warn("Could not delete video file:", fileErr?.message);
          }
        }
      }
    }

    if (lessonIds.length) {
      await TrainingLessonProgress.destroy({
        where: { TrainingLessonId: { [Op.in]: lessonIds } },
        transaction,
      });
    }

    if (moduleIds.length) {
      await TrainingModuleProgress.destroy({
        where: { TrainingModuleId: { [Op.in]: moduleIds } },
        transaction,
      });
    }

    await TrainingCourseEnrollment.destroy({
      where: { TrainingCourseId: courseId },
      transaction,
    });

    await TrainingModule.destroy({
      where: { TrainingCourseId: courseId },
      transaction,
    });

    await TrainingCourse.destroy({
      where: { id: courseId },
      transaction,
    });

    await transaction.commit();
    res.json({ message: "Course deleted successfully" });
  } catch (err) {
    await transaction.rollback();
    console.error("Error deleting course:", err);
    res.status(500).json({
      message: err.message || "Failed to delete course",
    });
  }
};

/**
 * POST /api/training-courses/admin/course/:courseId/module
 * Add a new module to an existing course
 */
const addModule = async (req, res) => {
  const { courseId } = req.params;
  const { title, description, order, lessons, quizzes } = req.body;

  try {
    const course = await TrainingCourse.findByPk(courseId);
    if (!course) {
      return res.status(404).json({ message: "Course not found" });
    }

    // Create module
    const module = await TrainingModule.create({
      TrainingCourseId: courseId,
      title,
      description,
      order: order || 0,
    });

    // Create lessons
    if (lessons && Array.isArray(lessons)) {
      for (const lessonData of lessons) {
        await TrainingLesson.create({
          TrainingModuleId: module.id,
          title: lessonData.title,
          description: lessonData.description,
          videoFileName: lessonData.videoFileName,
          youtubeId: lessonData.youtubeId,
          duration: lessonData.duration,
          watchUnlockPercent: lessonData.watchUnlockPercent || 80,
          order: lessonData.order || 0,
        });
      }
    }

    // Create quizzes
    if (quizzes && Array.isArray(quizzes)) {
      for (const quizData of quizzes) {
        await TrainingQuiz.create({
          TrainingModuleId: module.id,
          question: quizData.question,
          options: quizData.options,
          correctAnswer: quizData.correctAnswer,
          explanation: quizData.explanation,
          order: quizData.order || 0,
        });
      }
    }

    // Fetch complete module with relations
    const completeModule = await TrainingModule.findByPk(module.id, {
      include: [TrainingLesson, TrainingQuiz],
    });

    res.status(201).json(completeModule);
  } catch (err) {
    console.error("Error adding module:", err);
    res.status(500).json({ message: err.message || "Failed to add module" });
  }
};

/**
 * PATCH /api/training-courses/admin/course/:courseId/module/:moduleId
 * Update an existing module
 */
const updateModule = async (req, res) => {
  const { courseId, moduleId } = req.params;
  const { title, description, order } = req.body;

  try {
    const module = await TrainingModule.findOne({
      where: { id: moduleId, TrainingCourseId: courseId },
    });

    if (!module) {
      return res.status(404).json({ message: "Module not found" });
    }

    await TrainingModule.update(
      { title, description, order },
      { where: { id: moduleId, TrainingCourseId: courseId } },
    );

    const updated = await TrainingModule.findByPk(moduleId);
    res.json(updated);
  } catch (err) {
    console.error("Error updating module:", err);
    res.status(500).json({ message: "Failed to update module" });
  }
};

/**
 * DELETE /api/training-courses/admin/course/:courseId/module/:moduleId
 * Delete a module and all its lessons/quizzes
 */
const deleteModule = async (req, res) => {
  const { courseId, moduleId } = req.params;

  try {
    const module = await TrainingModule.findOne({
      where: { id: moduleId, TrainingCourseId: courseId },
      include: [TrainingLesson],
    });

    if (!module) {
      return res.status(404).json({ message: "Module not found" });
    }

    for (const lesson of module.TrainingLessons || []) {
      if (lesson.videoFileName) {
        try {
          deleteTrainingVideoFile(lesson.videoFileName);
        } catch (e) {
          console.warn("Could not delete video file:", e?.message);
        }
      }
    }

    await TrainingModule.destroy({
      where: { id: moduleId, TrainingCourseId: courseId },
    });
    res.json({ message: "Module deleted successfully" });
  } catch (err) {
    console.error("Error deleting module:", err);
    res.status(500).json({ message: "Failed to delete module" });
  }
};

module.exports = {
  // User endpoints
  getAllCourses,
  getCourseDetail,
  updateLessonProgress,
  checkQuizAnswer,
  completeModule,
  resetCourseProgress,
  getMyCertificates,
  // Admin endpoints
  createCourse,
  uploadLessonVideo,
  getAllCoursesAdmin,
  deleteCourse,
  addModule,
  updateModule,
  deleteModule,
};
