import diaryService from '../services/diaryService.js';
import HttpError from '../exceptions/HttpError.js';
import { devLog } from '../utils/logger.js';
import { emitDiaryDateUpdated, emitDiaryTagAdded, emitDiaryTagRemoved } from '../services/socketService.js';
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, excludeFromBilling } = 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, excludeFromBilling);
        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 { dateId, trainingStart, trainingEnd, excludeFromBilling } = req.body;
        if (!dateId) {
            devLog(dateId, trainingStart, trainingEnd, excludeFromBilling);
            throw new HttpError('notallfieldsfilled', 400);
        }
        const updatedDate = await diaryService.updateTrainingTimes(
            userToken,
            clubId,
            dateId,
            trainingStart,
            trainingEnd,
            excludeFromBilling,
        );
        
        // Emit Socket-Event
        emitDiaryDateUpdated(clubId, dateId, { trainingStart, trainingEnd, excludeFromBilling });
        
        res.status(200).json(updatedDate);
    } catch (error) {
        console.error('[updateTrainingTimes] - Error:', error);
        res.status(error.statusCode || 500).json({ error: error.message });
    }
};

const addDiaryNote = async (req, res) => {
    try {
        const { authcode: userToken } = req.headers;
        const { diaryDateId, content } = req.body;
        const notes = await diaryService.addNoteToDate(userToken, diaryDateId, content);
        res.status(201).json(notes);
    } catch (error) {
        console.error('[addDiaryNote] - Error:', error);
        res.status(500).json({ error: 'systemerror' });
    }
};

const deleteDiaryNote = async (req, res) => {
    try {
        const { authcode: userToken } = req.headers;
        const { noteId } = req.params;
        const notes = await diaryService.deleteNoteFromDate(userToken, noteId);
        res.status(200).json(notes);
    } catch (error) {
        console.error('[deleteDiaryNote] - Error:', error);
        res.status(500).json({ error: 'systemerror' });
    }
};

const addDiaryTag = async (req, res) => {
    try {
        const { authcode: userToken } = req.headers;
        const { diaryDateId, tagName } = req.body;
        const tags = await diaryService.addTagToDate(userToken, diaryDateId, tagName);
        
        // Hole clubId für Event
        const { DiaryDate } = await import('../models/index.js');
        const diaryDate = await DiaryDate.findByPk(diaryDateId);
        if (diaryDate?.clubId && tags && tags.length > 0) {
            emitDiaryTagAdded(diaryDate.clubId, diaryDateId, tags[tags.length - 1]);
        }
        
        res.status(201).json(tags);
    } catch (error) {
        console.error('[addDiaryTag] - Error:', error);
        res.status(500).json({ error: 'systemerror' });
    }
};

const addTagToDiaryDate = async (req, res) => {
    try {
        const { authcode: userToken } = req.headers;
        const { clubId } = req.params;  
        const { diaryDateId, tagId } = req.body;
        if (!diaryDateId || !tagId) {
            return res.status(400).json({ message: 'diaryDateId and tagId are required.' });
        }
        const result = await diaryService.addTagToDiaryDate(userToken, clubId, diaryDateId, tagId);
        
        // Emit Socket-Event
        if (result && result.tag) {
            emitDiaryTagAdded(clubId, diaryDateId, result.tag);
        }
        
        res.status(200).json(result);
    } catch (error) {
        console.error('[addTagToDiaryDate] - Error:', error);
        res.status(500).json({ message: 'An error occurred while adding the tag to the diary date.' });
    }
};

const deleteTagFromDiaryDate = async (req, res) => {
    try {
        const { tagId } = req.query;
        const { authcode: userToken } = req.headers;
        const { clubId } = req.params;
        
        // Hole diaryDateId vor dem Löschen
        const { DiaryDateTag } = await import('../models/index.js');
        const diaryDateTag = await DiaryDateTag.findByPk(tagId);
        const diaryDateId = diaryDateTag?.diaryDateId;
        
        await diaryService.removeTagFromDiaryDate(userToken, clubId, tagId);
        
        // Emit Socket-Event
        if (diaryDateId) {
            emitDiaryTagRemoved(clubId, diaryDateId, tagId);
        }
        
        res.status(200).json({ message: 'Tag deleted' });
    } catch (error) {
        console.error('[deleteTag] - Error:', error);
        res.status(500).json({ error: 'Error deleting tag' });
    }
};

export { getDatesForClub, createDateForClub, updateTrainingTimes, addDiaryNote, deleteDiaryNote, addDiaryTag,
    addTagToDiaryDate, deleteTagFromDiaryDate };

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