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

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

exports.addPosition = async (req, res) => {
  try {
    const { name } = req.body;
    if (!name) return res.status(400).json({ error: 'Position name is required' });

    const position = await Position.create({ name });
    res.status(201).json({ message: 'Position added successfully', position });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

exports.getPositionById = async (req, res) => {
    try {
        const { id } = req.params;
        const position = await Position.findByPk(id);
        if (position) {
            res.status(200).json({ actionStatus: 'Success', data: position });
        } else {
            res.status(404).json({ actionStatus: 'Failed', message: 'Product not found' });
        }
    } catch (error) {
        res.status(500).json({ actionStatus: 'Failed', message: error.message });
    }
};


exports.updatePosition = async (req, res) => {
  try {
    const { id } = req.params;
    const { name } = req.body;

    const position = await Position.findByPk(id);
    if (!position) return res.status(404).json({ error: 'Position not found' });

    position.name = name;
    await position.save();
    
    res.json({ message: 'Position updated successfully', position });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

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

    await position.destroy();
    res.json({ message: 'Position deleted successfully' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};