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

const getAllEventTypes = async (req, res) => {
  try {
    const eventTypes = await EventType.findAll({ order: [['caption', 'ASC']]});
    res.json(eventTypes);
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch event types' });
  }
};

const createEventType = async (req, res) => {
  try {
    const eventType = await EventType.create(req.body);
    res.status(201).json(eventType);
  } catch (error) {
    res.status(500).json({ error: 'Failed to create event type' });
  }
};

const updateEventType = async (req, res) => {
  try {
    const { id } = req.params;
    const [updated] = await EventType.update(req.body, {
      where: { id: id }
    });
    if (updated) {
      const updatedEventType = await EventType.findOne({ where: { id: id } });
      res.status(200).json(updatedEventType);
    } else {
      res.status(404).json({ error: 'Event type not found' });
    }
  } catch (error) {
    res.status(500).json({ error: 'Failed to update event type' });
  }
};

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

module.exports = {
  getAllEventTypes,
  createEventType,
  updateEventType,
  deleteEventType
};
