import DiaryService from '../services/diaryService.js';
import HttpError from '../exceptions/HttpError.js';

const diaryService = new DiaryService();

const getDatesForClub = async (req, res) => {
    try {
        const { clubId } = req.params;
        const { authcode: userToken } = req.headers;
        const dates = await diaryService.getDatesForClub(userToken, clubId);
        res.status(200).json(dates);
    } catch (error) {
        console.error('[getDatesForClub] - Error:', error);
        res.status(error.statusCode || 500).json({ error: error.message });
    }
};

const createDateForClub = async (req, res) => {
    try {
        const { clubId } = req.params;
        const { authcode: userToken } = req.headers;
        const { date, trainingStart, trainingEnd } = req.body;
        if (!date) {
            throw new HttpError('The date field is required', 400);
        }
        if (isNaN(new Date(date).getTime())) {
            throw new HttpError('Invalid date format', 400);
        }
        const newDate = await diaryService.createDateForClub(userToken, clubId, date, trainingStart, trainingEnd);
        res.status(201).json(newDate);
    } catch (error) {
        console.error('[createDateForClub] - Error:', error);
        res.status(error.statusCode || 500).json({ error: error.message });
    }
};


const updateTrainingTimes = async (req, res) => {
    try {
        const { clubId } = req.params;
        const { authcode: userToken } = req.headers;
        const { date, trainingStart, trainingEnd } = req.body;
        if (!date || !trainingStart) {
            throw new HttpError('notallfieldsfilled', 400);
        }
        const updatedDate = await diaryService.updateTrainingTimes(userToken, clubId, date, trainingStart, trainingEnd);
        res.status(200).json(updatedDate);
    } catch (error) {
        console.error('[updateTrainingTimes] - Error:', error);
        res.status(error.statusCode || 500).json({ error: error.message });
    }
};

export { getDatesForClub, createDateForClub, updateTrainingTimes };