import { DiaryNote, DiaryTag } from '../models/index.js';
import diaryService from '../services/diaryService.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, content, tags } = req.body;
        const newNote = await DiaryNote.create({ memberId, content });
        if (tags && tags.length > 0) {
            const tagInstances = await DiaryTag.findAll({ where: { id: tags } });
            await newNote.addTags(tagInstances);
        }
        const noteWithTags = await DiaryNote.findByPk(newNote.id, {
            include: [{ model: DiaryTag, as: 'tags' }],
        });
        res.status(201).json(noteWithTags);
    } catch (error) {
        res.status(500).json({ error: 'Error creating note' });
    }
};

export const deleteNote = async (req, res) => {
    try {
        const { noteId } = req.params;
        await DiaryNote.destroy({ where: { id: noteId } });
        res.status(200).json({ message: 'Note deleted' });
    } catch (error) {
        res.status(500).json({ error: 'Error deleting note' });
    }
};
