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

exports.createExam = async (req, res) => {
  try {
    const {
      name,
      shortName,
      examDate,
      applicationStartDate,
      applicationEndDate,
      level,
    } = req.body;

    const exam = await db.Exam.create({
      name,
      shortName,
      examDate,
      applicationStartDate,
      applicationEndDate,
      level,
    });

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

exports.getAllExams = async (req, res) => {
  try {
    const exams = await db.Exam.findAll({
      where: { isActive: true },
      order: [["display_order", "ASC"]],
    });

    res.json(exams);
  } catch (error) {
    res.status(500).json({
      success: false,
      error: "Failed to fetch exams",
    });
  }
};

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

    const [updated] = await db.Exam.update(updates, {
      where: { id },
    });

    if (!updated) {
      return res.status(404).json({
        success: false,
        error: "Exam not found",
      });
    }

    const updatedExam = await db.Exam.findByPk(id);
    res.json({
      success: true,
      data: updatedExam,
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message,
    });
  }
};

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

    const deleted = await db.Exam.destroy({
      where: { id },
    });

    if (!deleted) {
      return res.status(404).json({
        success: false,
        error: "Exam not found",
      });
    }

    res.json({
      success: true,
      message: "Exam deleted successfully",
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message,
    });
  }
};
