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

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

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

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

exports.update = async (req, res) => {
  try {
    const { PosName, RequiredQualification } = req.body;
    if (!PosName) {
      return res.status(400).json({ message: 'Position name is required' });
    }
    const position = await Position.findByIdAndUpdate(
      req.params.id,
      { PosName, RequiredQualification },
      { new: true, runValidators: true }
    );
    if (!position) {
      return res.status(404).json({ message: 'Position not found' });
    }
    res.json(position);
  } catch (error) {
    if (error.code === 11000) {
      return res.status(400).json({ message: 'Position 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({ Position: req.params.id });
    if (employeeCount > 0) {
      return res.status(400).json({
        message: `Cannot delete position. ${employeeCount} employee(s) hold this position.`
      });
    }
    const position = await Position.findByIdAndDelete(req.params.id);
    if (!position) {
      return res.status(404).json({ message: 'Position not found' });
    }
    res.json({ message: 'Position deleted successfully' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};
