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

const getAllEvents = async (req, res) => {
  try {
    const events = await Event.findAll({
      include: [
        { model: Institution, as: 'institution' },
        { model: EventPlace, as: 'eventPlace' },
        { model: ContactPerson, as: 'contactPersons', through: { attributes: [] } }
      ]
    });
    res.json(events);
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch events' });
    console.error(error);
  }
};

const createEvent = async (req, res) => {
  try {
    const { contactPersonIds, ...eventData } = req.body;
    const event = await Event.create(eventData);
    if (contactPersonIds) {
      await event.setContactPersons(contactPersonIds);
    }
    res.status(201).json(event);
  } catch (error) {
    res.status(500).json({ error: 'Failed to create event' });
    console.error(error);
  }
};

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

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

module.exports = {
  getAllEvents,
  createEvent,
  updateEvent,
  deleteEvent
};
