// controllers/gradeController.js

const db = require("../config/db"); // Keep for the 'in use' check
const Grade = require("../models/gradeModel");

exports.createGrade = async (req, res) => {
  try {
    const { institution_id } = req.user;
    const { name } = req.body;
    if (!name) return res.status(400).json({ message: "Grade name is required." });

    const grade = await Grade.create(institution_id, name);
    res.status(201).json({ message: "Grade created successfully", grade });
  } catch (error) {
    if (error.code === "ER_DUP_ENTRY") {
      return res.status(409).json({ message: "This grade already exists for your institution." });
    }
    res.status(500).json({ message: "Error creating grade", error: error.message });
  }
};

exports.getAllGrades = async (req, res) => {
  try {
    const { institution_id } = req.user;
    // You might want to pass a query param to include inactive grades, e.g., req.query.includeInactive
    const grades = await Grade.getAll(institution_id, req.query.includeInactive === 'true');
    res.status(200).json(grades);
  } catch (error) {
    res.status(500).json({ message: "Error fetching grades", error: error.message });
  }
};

exports.updateGrade = async (req, res) => {
  try {
    const { institution_id } = req.user;
    const { id } = req.params;
    const { name } = req.body;
    if (!name) return res.status(400).json({ message: "Grade name is required." });

    const success = await Grade.update(institution_id, id, name);
    if (success) {
      res.status(200).json({ message: "Grade updated successfully" });
    } else {
      res.status(404).json({ message: "Grade not found or no changes made" });
    }
  } catch (error) {
    res.status(500).json({ message: "Error updating grade", error: error.message });
  }
};

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

    // Check if grade is in use by any ACTIVE students within this institution
    const [rows] = await db.query(
      'SELECT 1 FROM students WHERE grade_id = ? AND status = "active" AND institution_id = ? LIMIT 1',
      [id, institution_id]
    );
    if (rows.length > 0) {
      return res.status(400).json({ message: "Cannot deactivate grade. It is currently assigned to active students." });
    }

    const success = await Grade.setStatus(institution_id, id, "inactive");
    if (success) {
      res.status(200).json({ message: "Grade deactivated successfully" });
    } else {
      res.status(404).json({ message: "Grade not found" });
    }
  } catch (error) {
    res.status(500).json({ message: "Error deactivating grade", error: error.message });
  }
};