const chalk = require('chalk');

module.exports = (client, db) => {
    setInterval(async () => {
        try {
            const now = Date.now();
            const [expiredMutes] = await db.query(
                'SELECT * FROM mutes WHERE type = ? AND unmuteDate <= ?',
                ['Temporary', now]
            );

            if (!expiredMutes.length) return;

            for (const mute of expiredMutes) {
                const guild = client.guilds.cache.get(mute.guildId);
                if (!guild) {
                    console.warn(chalk.yellow(`⚠️  Impossible de démuter ${mute.userId}: le bot n'est pas dans la guild ${mute.guildId}`));
                    continue;
                }

                const member = await guild.members.fetch(mute.userId).catch(() => null);
                if (!member) {
                    await db.query('DELETE FROM mutes WHERE userId = ? AND guildId = ?', [mute.userId, mute.guildId]);
                    continue;
                }

                try {
                    await member.timeout(null, 'Mute temporaire expiré');
                    console.log(chalk.green(`✅ Auto-démuté ${mute.userId} de la guild ${guild.name} (${guild.id})`));
                } catch (err) {
                    console.error(chalk.red(`❌ Échec du démute de ${mute.userId} de la guild ${guild.id}:`), err.message);
                }

                await db.query('DELETE FROM mutes WHERE userId = ? AND guildId = ?', [mute.userId, mute.guildId]);

                await db.query(
                    `INSERT INTO logs (userId, userTag, modId, modTag, action, reason, type, timestamp, guildId)
                     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
                    [mute.userId, null, client.user.id, client.user.tag, 'Unmute automatique', 'Mute temporaire expiré', 'Temporary', Date.now(), mute.guildId]
                );
            }

        } catch (err) {
            console.error(chalk.red('❌ Erreur lors de l\'auto-unmute:'), err);
        }
    }, 60_000);
};