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

const getAllContactPersons = async (req, res) => {
  try {
    const contactPersons = await ContactPerson.findAll({
      include: [
        {
          model: Position,
          as: 'positions',
          through: { attributes: [] }
        }
      ]
    });
    res.json(contactPersons);
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch contact persons' });
    console.error(error);
  }
};

const createContactPerson = async (req, res) => {
  try {
    const { positions, ...contactPersonData } = req.body;
    const contactPerson = await ContactPerson.create(contactPersonData);
    if (positions && positions.length > 0) {
      const positionIds = positions.map(position => position.id);
      await contactPerson.setPositions(positionIds);
    }
    res.status(201).json(contactPerson);
  } catch (error) {
    res.status(500).json({ error: 'Failed to create contact person' });
    console.error(error);
  }
};

const updateContactPerson = async (req, res) => {
  try {
    const { id } = req.params;
    const { positions, ...contactPersonData } = req.body;
    const contactPerson = await ContactPerson.findByPk(id);
    if (!contactPerson) {
      return res.status(404).json({ error: 'Contact person not found' });
    }
    await contactPerson.update(contactPersonData);
    if (positions && positions.length > 0) {
      const positionIds = positions.map(position => position.id);
      await contactPerson.setPositions(positionIds);
    }
    res.status(200).json(contactPerson);
  } catch (error) {
    res.status(500).json({ error: 'Failed to update contact person' });
    console.error(error);
  }
};

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

module.exports = {
  getAllContactPersons,
  createContactPerson,
  updateContactPerson,
  deleteContactPerson
};
