import DiaryDate from '../models/DiaryDates.js';
import Club from '../models/Club.js';
import { checkAccess } from '../utils/userUtils.js';
import HttpError from '../exceptions/HttpError.js';

class DiaryService {
    async getDatesForClub(userToken, clubId) {
        console.log('[DiaryService::getDatesForClub] - Check user access');
        await checkAccess(userToken, clubId);
        console.log('[DiaryService::getDatesForClub] - Validate club existence');
        const club = await Club.findByPk(clubId);
        if (!club) {
            throw new HttpError('Club not found', 404);
        }
        console.log('[DiaryService::getDatesForClub] - Load diary dates');
        const dates = await DiaryDate.findAll({
            where: { clubId },
            order: [['date', 'ASC'], ['trainingStart', 'ASC']]
        });

        return dates;
    }

    async createDateForClub(userToken, clubId, date, trainingStart, trainingEnd) {
        console.log('[DiaryService::createDateForClub] - Check user access');
        await checkAccess(userToken, clubId);
        console.log('[DiaryService::createDateForClub] - Validate club existence');
        const club = await Club.findByPk(clubId);
        if (!club) {
            throw new HttpError('Club not found', 404);
        }
        console.log('[DiaryService::createDateForClub] - Validate date');
        const parsedDate = new Date(date);
        if (isNaN(parsedDate.getTime())) {
            throw new HttpError('Invalid date format', 400);
        }
        if (trainingStart && trainingEnd && trainingStart >= trainingEnd) {
            throw new HttpError('Training start time must be before training end time', 400);
        }
        console.log('[DiaryService::createDateForClub] - Create new diary date');
        const newDate = await DiaryDate.create({
            date: parsedDate,
            clubId,
            trainingStart: trainingStart || null,
            trainingEnd: trainingEnd || null,    
        });

        return newDate;
    }

    async updateTrainingTimes(userToken, clubId, date, trainingStart, trainingEnd) {
        console.log('[DiaryService::updateTrainingTimes] - Check user access');
        await checkAccess(userToken, clubId);
        console.log('[DiaryService::updateTrainingTimes] - Validate date');
        const diaryDate = await DiaryDate.findOne({ where: { clubId, date } });
        if (!diaryDate) {
            throw new HttpError('Diary entry not found', 404);
        }
        if (trainingStart && trainingEnd && trainingStart >= trainingEnd) {
            throw new HttpError('Training start time must be before training end time', 400);
        }
        console.log('[DiaryService::updateTrainingTimes] - Update training times');
        diaryDate.trainingStart = trainingStart || null;
        diaryDate.trainingEnd = trainingEnd || null;
        await diaryDate.save();
        return diaryDate;
    }
}

export default DiaryService;
