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

exports.getAll = async (req, res) => {
  try {
    const departments = await Department.find().sort({ DepartName: 1 });
    res.json(departments);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

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

exports.create = async (req, res) => {
  try {
    const { DepartName } = req.body;
    if (!DepartName) {
      return res.status(400).json({ message: 'Department name is required' });
    }
    const department = await Department.create({ DepartName });
    res.status(201).json(department);
  } catch (error) {
    if (error.code === 11000) {
      return res.status(400).json({ message: 'Department already exists' });
    }
    res.status(500).json({ message: error.message });
  }
};

exports.update = async (req, res) => {
  try {
    const { DepartName } = req.body;
    if (!DepartName) {
      return res.status(400).json({ message: 'Department name is required' });
    }
    const department = await Department.findByIdAndUpdate(
      req.params.id,
      { DepartName },
      { new: true, runValidators: true }
    );
    if (!department) {
      return res.status(404).json({ message: 'Department not found' });
    }
    res.json(department);
  } catch (error) {
    if (error.code === 11000) {
      return res.status(400).json({ message: 'Department name already exists' });
    }
    res.status(500).json({ message: error.message });
  }
};

exports.remove = async (req, res) => {
  try {
    const Employee = require('../models/Employee');
    const employeeCount = await Employee.countDocuments({ Department: req.params.id });
    if (employeeCount > 0) {
      return res.status(400).json({
        message: `Cannot delete department. ${employeeCount} employee(s) belong to this department.`
      });
    }
    const department = await Department.findByIdAndDelete(req.params.id);
    if (!department) {
      return res.status(404).json({ message: 'Department not found' });
    }
    res.json({ message: 'Department deleted successfully' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};
