import calendarEventService from '../services/calendarEventService.js';
import { getSafeErrorMessage } from '../utils/errorUtils.js';

export const listClubCalendarEvents = async (req, res) => {
  try {
    const { authcode: userToken } = req.headers;
    const { clubId } = req.params;
    const { year } = req.query;
    const events = await calendarEventService.listClubEvents(userToken, clubId, year);
    res.status(200).json(events);
  } catch (error) {
    console.error('[listClubCalendarEvents] - Error:', error);
    const msg = getSafeErrorMessage(error, 'Fehler beim Laden der Kalender-Events');
    res.status(error.statusCode || 500).json({ error: msg });
  }
};

export const createClubCalendarEvent = async (req, res) => {
  try {
    const { authcode: userToken } = req.headers;
    const { clubId } = req.params;
    const event = await calendarEventService.createClubEvent(userToken, clubId, req.body, req.user?.id || null);
    res.status(201).json(event);
  } catch (error) {
    console.error('[createClubCalendarEvent] - Error:', error);
    const msg = getSafeErrorMessage(error, 'Fehler beim Speichern des Kalender-Events');
    res.status(error.statusCode || 500).json({ error: msg });
  }
};

export const updateClubCalendarEvent = async (req, res) => {
  try {
    const { authcode: userToken } = req.headers;
    const { clubId, eventId } = req.params;
    const event = await calendarEventService.updateClubEvent(userToken, clubId, eventId, req.body, req.user?.id || null);
    res.status(200).json(event);
  } catch (error) {
    console.error('[updateClubCalendarEvent] - Error:', error);
    const msg = getSafeErrorMessage(error, 'Fehler beim Speichern des Kalender-Events');
    res.status(error.statusCode || 500).json({ error: msg });
  }
};

export const deleteClubCalendarEvent = async (req, res) => {
  try {
    const { authcode: userToken } = req.headers;
    const { clubId, eventId } = req.params;
    const result = await calendarEventService.deleteClubEvent(userToken, clubId, eventId);
    res.status(200).json(result);
  } catch (error) {
    console.error('[deleteClubCalendarEvent] - Error:', error);
    const msg = getSafeErrorMessage(error, 'Fehler beim Löschen des Kalender-Events');
    res.status(error.statusCode || 500).json({ error: msg });
  }
};
