const DepartmentEmail = require("../models/DepartmentEmail");
const Program = require("../models/Program");

exports.getAllDepartmentEmails = async (req, res) => {
  try {
    const departmentEmails = await DepartmentEmail.find();
    res.json(departmentEmails);
  } catch (error) {
    console.error("Error fetching department emails:", error);
    res.status(500).json({ error: "Error fetching department emails" });
  }
};

exports.getDepartmentsByProgram = async (req, res) => {
  const program = await Program.findOne({ name: req.params.program });
  res.json(program ? program.departments : []);
};

exports.getEmailsByDepartment = async (req, res) => {
  const departmentEmails = await DepartmentEmail.findOne({ department: req.params.department });
  res.json(departmentEmails ? { emails: departmentEmails.emails } : { emails: [] });
};

exports.updateDepartmentEmails = async (req, res) => {
  const { department } = req.params;
  const { emails } = req.body;

  if (!emails || !Array.isArray(emails)) {
    return res.status(400).json({ error: "Emails array is required" });
  }

  try {
    const updatedDepartment = await DepartmentEmail.findOneAndUpdate(
      { department },
      { emails },
      { new: true, upsert: true }
    );
    res.json(updatedDepartment);
  } catch (error) {
    console.error("Error updating department emails:", error);
    res.status(500).json({ error: "Error updating department emails" });
  }
};

exports.createDepartment = async (req, res) => {
  const { department, emails, program } = req.body;

  if (!department || !emails || !Array.isArray(emails) || !program) {
    return res.status(400).json({ error: "Department, program, and emails array are required" });
  }

  try {
    const newDepartment = new DepartmentEmail({ department, emails });
    await newDepartment.save();

    await Program.findOneAndUpdate(
      { name: program },
      { $addToSet: { departments: department } },
      { upsert: true }
    );

    res.status(201).json(newDepartment);
  } catch (error) {
    console.error("Error creating department:", error);
    res.status(500).json({ error: "Error creating department" });
  }
};

exports.deleteDepartment = async (req, res) => {
  try {
    const { department } = req.params;
    await DepartmentEmail.findOneAndDelete({ department });
    res.json({ message: "Department deleted successfully" });
  } catch (error) {
    console.error("Error deleting department:", error);
    res.status(500).json({ error: "Error deleting department" });
  }
};
