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

const getAllPositions = async (req, res) => {
  try {
    const positions = await Position.findAll({order: [['caption', 'ASC']]});
    res.json(positions);
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch positions' });
  }
};

const createPosition = async (req, res) => {
  try {
    const position = await Position.create(req.body);
    res.status(201).json(position);
  } catch (error) {
    res.status(500).json({ error: 'Failed to create position' });
  }
};

const updatePosition = async (req, res) => {
  try {
    const { id } = req.params;
    const [updated] = await Position.update(req.body, {
      where: { id: id }
    });
    if (updated) {
      const updatedPosition = await Position.findOne({ where: { id: id } });
      res.status(200).json(updatedPosition);
    } else {
      res.status(404).json({ error: 'Position not found' });
    }
  } catch (error) {
    res.status(500).json({ error: 'Failed to update position' });
  }
};

const deletePosition = async (req, res) => {
  try {
    const { id } = req.params;
    const deleted = await Position.destroy({
      where: { id: id }
    });
    if (deleted) {
      res.status(204).json();
    } else {
      res.status(404).json({ error: 'Position not found' });
    }
  } catch (error) {
    res.status(500).json({ error: 'Failed to delete position' });
  }
};

module.exports = {
  getAllPositions,
  createPosition,
  updatePosition,
  deletePosition
};
