const { Events, ActivityType } = require('discord.js');
const { mClient } = require('..');

module.exports = {
    name: Events.ClientReady,
    once: true,
    async execute(client) {
        console.log(`Ready! Logged in as ${client.user.tag}`);

        // Set presence
        client.user.setPresence({
            activities: [{
                name: 'Red Dead Depression',
                type: ActivityType.Streaming,
                url: 'https://twitch.tv/desq_blocki'
            }],
            status: 'online'
        });

        // Check if a date matches today
        const isToday = (day, month) => {
            const today = new Date();
            return today.getDate() === day && today.getMonth() === month - 1;
        };

        // Handle birthdays
        const handleBirthdays = async () => {
            const guild = await client.guilds.fetch(process.env.D_GuildID);
            const db = mClient.db(process.env.M_DB);

            const bdayColl = db.collection('items_birthdays');
            const allBirthdays = await bdayColl.find().toArray();
            const bdayMap = new Map(allBirthdays.map(b => [b.userID, b]));

            // Fetch birthday role
            const bdayRoleColl = db.collection('config_roles');
            const bdayRoleEntry = await bdayRoleColl.findOne({ guildID: guild.id });
            const birthdayRoleID = bdayRoleEntry?.roleID;

            if (!birthdayRoleID) {
                console.warn("No birthday role configured in DB");
                return;
            }

            // Fetch all guild members
            const members = await guild.members.fetch();

            for (const member of members.values()) {
                const dbEntry = bdayMap.get(member.id);

                if (!dbEntry) continue;

                // Reset notification once the birthday has passed
                if (!isToday(dbEntry.day, dbEntry.month) && dbEntry.notified) {
                    await bdayColl.updateOne(
                        { userID: member.id },
                        { $set: { notified: false } }
                    );

                    dbEntry.notified = false; // keep local copy in sync
                    console.log(`Removed notified flag for ${member.user.tag}`);
                }

                // Skip if already handled today
                if (dbEntry.notified && isToday(dbEntry.day, dbEntry.month)) {
                    console.log(`${member.user.username} was already notified today, skipping...`);
                    continue;
                }

                if (isToday(dbEntry.day, dbEntry.month)) {
                    await member.roles.add(birthdayRoleID).catch(err =>
                        console.error(`Failed to add birthday role to ${member.user.tag}:`, err)
                    );

                    console.log(`Added birthday role to ${member.user.tag}`);
                    client.emit('Birthday', member);

                    // mark as notified
                    await bdayColl.updateOne(
                        { userID: member.id },
                        { $set: { notified: true } }
                    );

                } else {
                    if (member.roles.cache.has(birthdayRoleID)) {
                        await member.roles.remove(birthdayRoleID).catch(err =>
                            console.error(`Failed to remove birthday role from ${member.user.tag}:`, err)
                        );

                        console.log(`Removed birthday role from ${member.user.tag}`);
                    }
                }
            }
        };

        await handleBirthdays();

        // First check after restart
        client.emit('timerCheck');

        // Check every minute
        setInterval(() => {
            client.emit('timerCheck');
        }, 60_000);
    }
};