const Department = require('../models/Department');

exports.addDepartment = async (req, res) => {
  try {
    const { departmentName } = req.body;

    if (!departmentName) {
      return res.status(400).json({ message: 'Department name is required' });
    }

    const existing = await Department.findOne({ departmentName: departmentName.trim() });
    if (existing) {
      return res.status(409).json({ message: 'Department already exists' });
    }

    const dept = await Department.create({ departmentName: departmentName.trim() });
    res.status(201).json(dept);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

exports.getDepartments = async (req, res) => {
  try {
    const departments = await Department.find();
    res.json(departments);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

exports.updateDepartment = async (req, res) => {
  try {
    const { departmentName } = req.body;

    if (!departmentName) {
      return res.status(400).json({ message: 'Department name is required' });
    }

    const department = await Department.findById(req.params.id);
    if (!department) {
      return res.status(404).json({ message: 'Department not found' });
    }

    const existing = await Department.findOne({
      departmentName: departmentName.trim(),
      _id: { $ne: req.params.id },
    });
    if (existing) {
      return res.status(409).json({ message: 'Department already exists' });
    }

    department.departmentName = departmentName.trim();
    await department.save();

    res.json(department);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

exports.deleteDepartment = async (req, res) => {
  try {
    const department = await Department.findById(req.params.id);
    if (!department) {
      return res.status(404).json({ message: 'Department not found' });
    }

    await Department.findByIdAndDelete(req.params.id);
    res.json({ message: 'Department deleted successfully' });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};
