import DiaryDate from "../models/DiaryDates.js";
import DiaryDateTag from "../models/DiaryDateTag.js";
import DiaryMemberTag from "../models/DiaryMemberTag.js";
import { DiaryTag } from "../models/DiaryTag.js";
import Member from "../models/Member.js";
import { checkAccess } from '../utils/userUtils.js';
import { Op, literal } from "sequelize";

import { devLog } from '../utils/logger.js';
class DiaryDateTagService {
    async getDiaryDateMemberTags(userToken, clubId, memberId) {
        await checkAccess(userToken, clubId);
        return await DiaryTag.findAll({
            include: [
                {
                    model: DiaryMemberTag,
                    as: 'diaryMemberTags',
                    where: { memberId },
                    required: true, 
                    include: [
                        {
                            model: DiaryDate,
                            as: 'diaryDates',
                            required: true,
                            on: {
                                '$diaryMemberTags.diary_date_id$': { [Op.eq]: literal('`diaryMemberTags->diaryDates`.`id`') }
                            }
                        }
                    ]
                }
            ],
            order: [[literal('`diaryMemberTags->diaryDates`.`date`'), 'DESC']],
            group: ['DiaryTag.id'],
            having: literal('COUNT(DISTINCT `diaryMemberTags->diaryDates`.`id`) >= 1'),
        });
    }

    async addDiaryDateTag(userToken, clubId, diaryDateId, memberId, tag) {
        devLog(userToken, clubId, diaryDateId, memberId, tag);
        await checkAccess(userToken, clubId);
        const tagObject = await DiaryTag.findOne({ where: { id: tag.id } });
        if (!tagObject) {
            throw new Error('Tag not found');
        }
        const diaryDate = await DiaryDate.findByPk(diaryDateId);
        if (!diaryDate) {
            throw new Error('DiaryDate not found');
        }
        const member = await Member.findByPk(memberId);
        if (!member) {
            throw new Error('Member not found');
        }
        const existingTag = await DiaryMemberTag.findOne({ where: { diaryDateId, memberId, tagId: tag.id } });
        if (!existingTag) {
            await DiaryMemberTag.create({ diaryDateId, memberId, tagId: tag.id });
        }
        return await this.getDiaryDateMemberTags(userToken, clubId, memberId);
    }
}

export default new DiaryDateTagService();
