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

// In your controller
exports.createStudyGoal = async (req, res) => {
  try {
    const { title, slug, programs = [], ...otherFields } = req.body;

    // Use transaction for atomic operations
    const result = await db.sequelize.transaction(async (t) => {
      // 1. Create StudyGoal
      const studyGoal = await db.StudyGoal.create(
        {
          title,
          slug,
          ...otherFields,
        },
        { transaction: t }
      );

      // 2. Add programs if they exist
      if (programs.length > 0) {
        const programsData = programs.map((program) => ({
          ...program,
          study_goal_id: studyGoal.id,
        }));
        await db.StudyGoalProgram.bulkCreate(programsData, { transaction: t });
      }

      // 3. Return the complete object with programs
      return db.StudyGoal.findByPk(studyGoal.id, {
        include: [
          {
            model: db.StudyGoalProgram,
            as: "programs",
          },
        ],
        transaction: t,
      });
    });

    res.status(201).json({
      success: true,
      data: result,
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message,
    });
  }
};

exports.getStudyGoals = async (req, res) => {
  try {
    const studyGoals = await db.StudyGoal.findAll({
      where: { isActive: true },
      include: [
        {
          model: db.StudyGoalProgram,
          as: "programs",
          where: { isActive: true },
          required: false,
        },
      ],
      order: [
        ["display_order", "ASC"],
        [{ model: db.StudyGoalProgram, as: "programs" }, "name", "ASC"],
      ],
    });

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

exports.addProgramToGoal = async (req, res) => {
  try {
    const { studyGoalId } = req.params;
    const { name, collegeCount } = req.body;

    if (!name) {
      return res.status(400).json({ error: "Program name is required" });
    }

    const program = await db.StudyGoalProgram.create({
      name,
      collegeCount: collegeCount || 0,
      studyGoalId,
    });

    res.status(201).json({
      success: true,
      message: "Program added successfully",
      data: program,
    });
  } catch (err) {
    console.error("Error adding program:", err);
    res.status(500).json({ error: "Failed to add program" });
  }
};

exports.deleteStudyGoal = async (req, res) => {
  try {
    const { id } = req.params;

    // Using transaction to ensure data consistency
    await db.sequelize.transaction(async (t) => {
      // First delete all associated programs
      await db.StudyGoalProgram.destroy({
        where: { study_goal_id: id },
        transaction: t,
      });

      // Then delete the study goal
      const deletedCount = await db.StudyGoal.destroy({
        where: { id },
        transaction: t,
      });

      if (deletedCount === 0) {
        throw new Error("Study goal not found");
      }
    });

    res.status(200).json({
      success: true,
      message: "Study goal and its programs deleted successfully",
    });
  } catch (error) {
    console.error("Error deleting study goal:", error);
    res.status(500).json({
      success: false,
      error: error.message || "Failed to delete study goal",
    });
  }
};
