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

const getAllInstitutions = async (req, res) => {
  try {
    const institutions = await Institution.findAll({
      include: [
        {
          model: ContactPerson,
          as: 'contactPersons',
          through: { attributes: [] }
        }
      ],
      order: [['name', 'ASC']]
    });
    res.json(institutions);
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch institutions' });
    console.error(error);
  }
};

const getInstitutionById = async (req, res) => {
  try {
    const { id } = req.params;
    const institution = await Institution.findByPk(id, {
      include: [
        {
          model: ContactPerson,
          as: 'contactPersons',
          through: { attributes: [] }
        }
      ]
    });
    if (!institution) {
      return res.status(404).json({ error: 'Institution not found' });
    }
    res.json(institution);
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch institution' });
    console.error(error);
  }
};

const createInstitution = async (req, res) => {
  try {
    const { contactPersonIds, ...institutionData } = req.body;
    const institution = await Institution.create(institutionData);
    if (contactPersonIds) {
      await institution.setContactPersons(contactPersonIds);
    }
    res.status(201).json(institution);
  } catch (error) {
    res.status(500).json({ error: 'Failed to create institution' });
    console.error(error);
  }
};

const updateInstitution = async (req, res) => {
  try {
    const { id } = req.params;
    const { contactPersonIds, ...institutionData } = req.body;
    const institution = await Institution.findByPk(id);
    if (!institution) {
      return res.status(404).json({ error: 'Institution not found' });
    }
    await institution.update(institutionData);
    if (contactPersonIds) {
      await institution.setContactPersons(contactPersonIds);
    }
    res.status(200).json(institution);
  } catch (error) {
    res.status(500).json({ error: 'Failed to update institution' });
    console.error(error);
  }
};

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

module.exports = {
  getAllInstitutions,
  getInstitutionById,
  createInstitution,
  updateInstitution,
  deleteInstitution
};
