const db = require("../../db");
const { Op } = require("sequelize");

exports.createStudent = async (req, res) => {
  try {
    const studentData = req.body;

    // Validate appling_for field
    if (!["MBA", "UG"].includes(studentData.appling_for)) {
      return res
        .status(400)
        .json({ error: "appling_for must be either 'MBA' or 'UG'" });
    }

    const student = await db.Student.create(studentData);
    res.status(201).json(student);
  } catch (error) {
    console.error("Error creating student:", error);
    res.status(500).json({ error: "Failed to create student" });
  }
};

exports.getStudents = async (req, res) => {
  try {
    const { appling_for, search } = req.query;
    const where = {};

    if (appling_for) {
      where.appling_for = appling_for;
    }

    if (search) {
      where[Op.or] = [
        { first_name: { [Op.like]: `%${search}%` } },
        { last_name: { [Op.like]: `%${search}%` } },
        { email_id: { [Op.like]: `%${search}%` } },
      ];
    }

    const students = await db.Student.findAll({ where });
    res.json(students);
  } catch (error) {
    console.error("Error fetching students:", error);
    res.status(500).json({ error: "Failed to fetch students" });
  }
};

exports.getStudentById = async (req, res) => {
  try {
    const student = await db.Student.findByPk(req.params.id);
    if (!student) {
      return res.status(404).json({ error: "Student not found" });
    }
    res.json(student);
  } catch (error) {
    console.error("Error fetching student:", error);
    res.status(500).json({ error: "Failed to fetch student" });
  }
};

exports.updateStudent = async (req, res) => {
  try {
    const [updated] = await db.Student.update(req.body, {
      where: { student_id: req.params.id },
    });

    if (!updated) {
      return res.status(404).json({ error: "Student not found" });
    }

    const updatedStudent = await db.Student.findByPk(req.params.id);
    res.json(updatedStudent);
  } catch (error) {
    console.error("Error updating student:", error);
    res.status(500).json({ error: "Failed to update student" });
  }
};

exports.deleteStudent = async (req, res) => {
  try {
    const deleted = await db.Student.destroy({
      where: { student_id: req.params.id },
    });

    if (!deleted) {
      return res.status(404).json({ error: "Student not found" });
    }

    res.status(204).send();
  } catch (error) {
    console.error("Error deleting student:", error);
    res.status(500).json({ error: "Failed to delete student" });
  }
};

// Get student count by category
exports.getStudentStats = async (req, res) => {
  try {
    const stats = await db.Student.findAll({
      attributes: [
        "appling_for",
        [sequelize.fn("COUNT", sequelize.col("student_id")), "count"],
      ],
      group: ["appling_for"],
    });

    res.json(stats);
  } catch (error) {
    console.error("Error fetching student stats:", error);
    res.status(500).json({ error: "Failed to fetch student statistics" });
  }
};
