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

exports.addPosition = async (req, res) => {
  try {
    const { posName, requiredQualification } = req.body;

    if (!posName || !requiredQualification) {
      return res.status(400).json({ message: 'Position name and qualification are required' });
    }

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

    const position = await Position.create({
      posName: posName.trim(),
      requiredQualification: requiredQualification.trim(),
    });
    res.status(201).json(position);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

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

exports.updatePosition = async (req, res) => {
  try {
    const { posName, requiredQualification } = req.body;

    if (!posName || !requiredQualification) {
      return res.status(400).json({ message: 'Position name and qualification are required' });
    }

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

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

    position.posName = posName.trim();
    position.requiredQualification = requiredQualification.trim();
    await position.save();

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

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

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