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

function validateDepartmentBody(body) {
  const { departmentCode, departmentName } = body || {};
  if (!departmentCode || typeof departmentCode !== 'string' || departmentCode.trim().length < 2) {
    return 'departmentCode is required and must be at least 2 characters';
  }
  if (!departmentName || typeof departmentName !== 'string' || departmentName.trim().length < 2) {
    return 'departmentName is required and must be at least 2 characters';
  }
  return null;
}

async function createDepartment(req, res, next) {
  try {
    const errMsg = validateDepartmentBody(req.body);
    if (errMsg) return res.status(400).json({ message: errMsg });

    const existing = await Department.findOne({ departmentCode: req.body.departmentCode.trim() });
    if (existing) return res.status(400).json({ message: 'departmentCode already exists' });

    const dep = await Department.create({
      departmentCode: req.body.departmentCode.trim(),
      departmentName: req.body.departmentName.trim()
    });

    return res.status(201).json(dep);
  } catch (err) {
    return next(err);
  }
}

async function getAllDepartments(req, res, next) {
  try {
    const deps = await Department.find().sort({ createdAt: -1 });
    return res.status(200).json(deps);
  } catch (err) {
    return next(err);
  }
}

async function updateDepartment(req, res, next) {
  try {
    const { id } = req.params;
    const errMsg = validateDepartmentBody(req.body);
    if (errMsg) return res.status(400).json({ message: errMsg });

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

    // Unique code check
    const other = await Department.findOne({ departmentCode: req.body.departmentCode.trim(), _id: { $ne: id } });
    if (other) return res.status(400).json({ message: 'departmentCode already exists' });

    dep.departmentCode = req.body.departmentCode.trim();
    dep.departmentName = req.body.departmentName.trim();

    await dep.save();
    return res.status(200).json(dep);
  } catch (err) {
    return next(err);
  }
}

async function deleteDepartment(req, res, next) {
  try {
    const { id } = req.params;
    const dep = await Department.findByIdAndDelete(id);
    if (!dep) return res.status(404).json({ message: 'Department not found' });
    return res.status(200).json({ message: 'Department deleted successfully' });
  } catch (err) {
    return next(err);
  }
}

module.exports = {
  createDepartment,
  getAllDepartments,
  updateDepartment,
  deleteDepartment
};

