const chalk = require('chalk');

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;

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

                try {
                    await guild.members.unban(ban.userId, 'Bannissement temporaire expiré');
                    console.log(chalk.green(`✅ Auto-débanni ${ban.userId} de la guild ${guild.name} (${guild.id})`));
                } catch (err) {
                    console.error(chalk.red(`❌ Échec du débannissement de ${ban.userId} de la guild ${guild.id}:`), err.message);
                }

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

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

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