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

export const getTrainingCancellations = async (req, res) => {
  try {
    const { authcode: userToken } = req.headers;
    const { clubId } = req.params;
    const { year } = req.query;
    const result = await trainingCancellationService.getTrainingCancellations(userToken, clubId, year);
    res.status(200).json(result);
  } catch (error) {
    console.error('[getTrainingCancellations] - Error:', error);
    const message = getSafeErrorMessage(error, 'Fehler beim Laden der Trainingsausfälle');
    res.status(error.statusCode || 500).json({ error: message });
  }
};

export const upsertTrainingCancellation = async (req, res) => {
  try {
    const { authcode: userToken } = req.headers;
    const { clubId } = req.params;
    const { date, startDate, endDate, reason, trainingGroupIds } = req.body;
    const result = await trainingCancellationService.upsertTrainingCancellation(
      userToken,
      clubId,
      startDate || date,
      reason,
      endDate || date || startDate,
      trainingGroupIds
    );
    res.status(200).json(result);
  } catch (error) {
    console.error('[upsertTrainingCancellation] - Error:', error);
    const message = getSafeErrorMessage(error, 'Fehler beim Speichern des Trainingsausfalls');
    res.status(error.statusCode || 500).json({ error: message });
  }
};

export const deleteTrainingCancellation = async (req, res) => {
  try {
    const { authcode: userToken } = req.headers;
    const { clubId, cancellationId } = req.params;
    const result = await trainingCancellationService.deleteTrainingCancellation(userToken, clubId, cancellationId);
    res.status(200).json(result);
  } catch (error) {
    console.error('[deleteTrainingCancellation] - Error:', error);
    const message = getSafeErrorMessage(error, 'Fehler beim Löschen des Trainingsausfalls');
    res.status(error.statusCode || 500).json({ error: message });
  }
};
