import DiaryMemberNote from '../models/DiaryMemberNote.js';
import DiaryMemberTag from '../models/DiaryMemberTag.js';
import { DiaryTag } from '../models/DiaryTag.js';
import { checkAccess } from '../utils/userUtils.js';

import { devLog } from '../utils/logger.js';
class DiaryMemberService {
    async addNoteToMember(userToken, clubId, diaryDateId, memberId, content) {
        await checkAccess(userToken, clubId);
        const existingNote = await DiaryMemberNote.findOne({ where: { diaryDateId, memberId, content } });
        if (!existingNote) {
            await DiaryMemberNote.create({ diaryDateId, memberId, content });
        }
    }

    async getNotesForMember(userToken, clubId, diaryDateId, memberId) {
        await checkAccess(userToken, clubId);
        devLog(clubId, diaryDateId, memberId);
        return await DiaryMemberNote.findAll({ where: { diaryDateId, memberId }, order: [['createdAt', 'DESC']] });
    }

    async addTagToMemberAndDate(userToken, clubId, diaryDateId, memberId, tagId) {
        await checkAccess(userToken, clubId);
        const existingTag = await DiaryMemberTag.findOne({ where: { diaryDateId, memberId, tagId } });
        if (!existingTag) {
            await DiaryMemberTag.create({ diaryDateId, memberId, tagId });
        }
    }

    async getTagsForMemberAndDate(userToken, clubId, diaryDateId, memberId) {
        await checkAccess(userToken, clubId);
        return await DiaryMemberTag.findAll({
            where: { diaryDateId, memberId },
            include: [{ model: DiaryTag, as: 'tag' }]
        });
    }

    async removeNoteFromMember(userToken, clubId, noteId) {
        await checkAccess(userToken, clubId);
        const note = await DiaryMemberNote.findOne({ where: { id: noteId } });
        if (note) {
            await note.destroy();
        } else {
            throw new Error('Die Notiz existiert nicht.');
        }
    }

    async removeTagFromMemberAndDate(userToken, clubId, diaryDateId, memberId, tag) {
        await checkAccess(userToken, clubId);
        const tagLink = await DiaryMemberTag.findOne({ where: { diaryDateId, memberId, tagId: tag.id } });
        if (tagLink) {
            await tagLink.destroy();
        } else {
            devLog(diaryDateId, memberId, tag?.id);
            throw new Error('Das Tag ist nicht verknüpft.');
        }
    }

}

export default new DiaryMemberService();
