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

const getAllEventPlaces = async (req, res) => {
  try {
    const eventPlaces = await EventPlace.findAll({
      order: [['name', 'ASC']]
    });
    res.json(eventPlaces);
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch event places' });
  }
};

const createEventPlace = async (req, res) => {
  try {
    const eventPlace = await EventPlace.create(req.body);
    res.status(201).json(eventPlace);
  } catch (error) {
    res.status(500).json({ error: 'Failed to create event place' });
  }
};

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

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

module.exports = {
  getAllEventPlaces,
  createEventPlace,
  updateEventPlace,
  deleteEventPlace
};
