const db = require("../db");

// 1. Create Course
async function createCourse(req, res) {
  try {
    const requiredFields = [
      "name",
      "programType",
      "studyMode",
      "duration",
      "feesIndian",
    ];
    const missingFields = requiredFields.filter((field) => !req.body[field]);

    if (missingFields.length > 0) {
      return res.status(400).json({
        error: "Missing required fields",
        missingFields,
      });
    }

    const course = await db.Course.create(req.body);
    res.status(201).json({
      success: true,
      message: "Course created successfully",
      data: course,
    });
  } catch (err) {
    console.error("Error:", err);
    res.status(500).json({
      success: false,
      error: "Failed to create course",
    });
  }
}

// 2. Get All Courses
async function getCourses(req, res) {
  try {
    const { programType, studyMode } = req.query;
    const where = {};

    if (programType) where.programType = programType;
    if (studyMode) where.studyMode = studyMode;

    const courses = await db.Course.findAll({
      where,
      order: [["name", "ASC"]],
    });

    // Group by program type for frontend display
    const groupedCourses = courses.reduce((acc, course) => {
      const key = course.programType;
      if (!acc[key]) {
        acc[key] = [];
      }
      acc[key].push(course);
      return acc;
    }, {});

    res.json({
      success: true,
      data: groupedCourses,
    });
  } catch (err) {
    console.error("Error:", err);
    res.status(500).json({
      success: false,
      error: "Failed to fetch courses",
    });
  }
}

// 3. Get Single Course by ID
async function getCourseById(req, res) {
  try {
    const course = await db.Course.findByPk(req.params.id);
    if (!course) {
      return res.status(404).json({
        success: false,
        error: "Course not found",
      });
    }
    res.json({
      success: true,
      data: course,
    });
  } catch (err) {
    console.error("Error:", err);
    res.status(500).json({
      success: false,
      error: "Failed to fetch course",
    });
  }
}

// 4. Update Course
async function updateCourse(req, res) {
  try {
    const course = await db.Course.findByPk(req.params.id);
    if (!course) {
      return res.status(404).json({
        success: false,
        error: "Course not found",
      });
    }

    await course.update(req.body);
    res.json({
      success: true,
      message: "Course updated successfully",
      data: course,
    });
  } catch (err) {
    console.error("Error:", err);
    res.status(500).json({
      success: false,
      error: "Failed to update course",
    });
  }
}

// 5. Delete Course
async function deleteCourse(req, res) {
  try {
    const course = await db.Course.findByPk(req.params.id);
    if (!course) {
      return res.status(404).json({
        success: false,
        error: "Course not found",
      });
    }

    await course.destroy();
    res.json({
      success: true,
      message: "Course deleted successfully",
    });
  } catch (err) {
    console.error("Error:", err);
    res.status(500).json({
      success: false,
      error: "Failed to delete course",
    });
  }
}

// Export all controller methods
module.exports = {
  createCourse,
  getCourses,
  getCourseById,
  updateCourse,
  deleteCourse,
};
