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

export const getTrainingTimes = async (req, res) => {
    try {
        const { authcode: userToken } = req.headers;
        const { clubId } = req.params;
        const groups = await trainingTimeService.getTrainingTimes(userToken, clubId);
        res.status(200).json(groups);
    } catch (error) {
        console.error('[getTrainingTimes] - Error:', error);
        const msg = getSafeErrorMessage(error, 'Fehler beim Laden der Trainingszeiten');
        res.status(error.statusCode || 500).json({ error: msg });
    }
};

export const createTrainingTime = async (req, res) => {
    try {
        const { authcode: userToken } = req.headers;
        const { clubId } = req.params;
        const { trainingGroupId, weekday, startTime, endTime } = req.body;
        
        if (!trainingGroupId || weekday === undefined || !startTime || !endTime) {
            return res.status(400).json({ error: 'Alle Felder müssen ausgefüllt sein' });
        }
        
        const trainingTime = await trainingTimeService.createTrainingTime(
            userToken,
            clubId,
            trainingGroupId,
            weekday,
            startTime,
            endTime
        );
        
        res.status(201).json(trainingTime);
    } catch (error) {
        console.error('[createTrainingTime] - Error:', error);
        const msg = getSafeErrorMessage(error, 'Fehler beim Erstellen der Trainingszeit');
        res.status(error.statusCode || 500).json({ error: msg });
    }
};

export const updateTrainingTime = async (req, res) => {
    try {
        const { authcode: userToken } = req.headers;
        const { clubId, timeId } = req.params;
        const { weekday, startTime, endTime } = req.body;
        
        const trainingTime = await trainingTimeService.updateTrainingTime(
            userToken,
            clubId,
            timeId,
            weekday,
            startTime,
            endTime
        );
        
        res.status(200).json(trainingTime);
    } catch (error) {
        console.error('[updateTrainingTime] - Error:', error);
        const msg = getSafeErrorMessage(error, 'Fehler beim Aktualisieren der Trainingszeit');
        res.status(error.statusCode || 500).json({ error: msg });
    }
};

export const deleteTrainingTime = async (req, res) => {
    try {
        const { authcode: userToken } = req.headers;
        const { clubId, timeId } = req.params;
        
        const result = await trainingTimeService.deleteTrainingTime(userToken, clubId, timeId);
        res.status(200).json(result);
    } catch (error) {
        console.error('[deleteTrainingTime] - Error:', error);
        const msg = getSafeErrorMessage(error, 'Fehler beim Löschen der Trainingszeit');
        res.status(error.statusCode || 500).json({ error: msg });
    }
};

