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

            if (!expiredBans.length) return; // rien à faire

            for (const ban of expiredBans) {
                const guild = client.guilds.cache.get(ban.guildId);
                if (!guild) {
                    console.warn(`Cannot unban ${ban.userId}: bot is not in guild ${ban.guildId}`);
                    continue;
                }

                try {
                    await guild.members.unban(ban.userId, 'Temporary ban expired');
                    console.log(`Auto-unbanned ${ban.userId} from guild ${guild.id}`);
                } catch (err) {
                    // Si l’utilisateur n’est pas ban ou autre erreur
                    console.error(`Failed to unban ${ban.userId} from guild ${guild.id}:`, err.message);
                }

                // Supprime uniquement le ban correspondant à cette guild
                await db.query('DELETE FROM bans WHERE userId = ? AND guildId = ?', [ban.userId, ban.guildId]);

                // Log automatique
                await db.query(
                    `INSERT INTO logs (userId, userTag, modId, modTag, action, reason, type, timestamp, guildId)
                     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
                    [ban.userId, null, client.user.id, 'Fembot', 'auto-unban', 'Temporary ban expired', 'Temporary', Date.now(), ban.guildId]
                );
            }

        } catch (err) {
            console.error('Error during auto-unban:', err);
        }
    }, 60_000);
};
