import { DiaryNote, DiaryTag, DiaryDate } from '../models/index.js';
import diaryService from '../services/diaryService.js';
import { emitDiaryNoteAdded, emitDiaryNoteDeleted } from '../services/socketService.js';

export const getNotes = async (req, res) => {
    try {
        const { diaryDateId, memberId } = req.query;
        if (!diaryDateId || !memberId) {
            return res.status(400).json({ error: 'diaryDateId and memberId are required.' });
        }

        const notes = await diaryService.getDiaryNotesForDateAndMember(diaryDateId, memberId);
        res.status(200).json(notes);
    } catch (error) {
        console.error('[getNotes] - Error:', error);
        res.status(500).json({ error: 'An error occurred while fetching the notes.' });
    }
};

export const createNote = async (req, res) => {
    try {
        const { memberId, diaryDateId, content, tags } = req.body;

        if (!memberId || !diaryDateId || !content) {
            return res.status(400).json({ error: 'memberId, diaryDateId und content sind erforderlich.' });
        }

        const newNote = await DiaryNote.create({ memberId, diaryDateId, content });

        // Hole DiaryDate für clubId
        const diaryDate = await DiaryDate.findByPk(diaryDateId);
        
        if (Array.isArray(tags) && tags.length > 0 && typeof newNote.addTags === 'function') {
            const tagInstances = await DiaryTag.findAll({ where: { id: tags } });
            await newNote.addTags(tagInstances);

            const noteWithTags = await DiaryNote.findByPk(newNote.id, {
                include: [{ model: DiaryTag, as: 'tags', required: false }],
            });

            // Emit Socket-Event
            if (diaryDate?.clubId) {
                emitDiaryNoteAdded(diaryDate.clubId, diaryDateId, noteWithTags ?? newNote);
            }

            return res.status(201).json(noteWithTags ?? newNote);
        }

        // Emit Socket-Event
        if (diaryDate?.clubId) {
            emitDiaryNoteAdded(diaryDate.clubId, diaryDateId, newNote);
        }

        res.status(201).json(newNote);
    } catch (error) {
        console.error('[createNote] - Error:', error);
        res.status(500).json({ error: 'Error creating note' });
    }
};

export const deleteNote = async (req, res) => {
    try {
        const { noteId } = req.params;
        
        // Hole Note für diaryDateId vor dem Löschen
        const note = await DiaryNote.findByPk(noteId);
        const diaryDateId = note?.diaryDateId;
        
        // Hole DiaryDate für clubId
        let clubId = null;
        if (diaryDateId) {
            const diaryDate = await DiaryDate.findByPk(diaryDateId);
            clubId = diaryDate?.clubId;
        }
        
        await DiaryNote.destroy({ where: { id: noteId } });
        
        // Emit Socket-Event
        if (clubId && diaryDateId) {
            emitDiaryNoteDeleted(clubId, diaryDateId, noteId);
        }
        
        res.status(200).json({ message: 'Note deleted' });
    } catch (error) {
        res.status(500).json({ error: 'Error deleting note' });
    }
};
