require('dotenv').config();

const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, GatewayIntentBits } = require('discord.js');
const chalk = require('chalk');

const token = process.env.TOKEN;

if (!token) {
    console.error(chalk.red('❌ Le token Discord n\'est pas défini dans les variables d\'environnement !'));
    process.exit(1);
}

const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMembers,
        GatewayIntentBits.GuildPresences,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent,
        GatewayIntentBits.GuildVoiceStates,
    ],
});

const db = require('./functions/database/db.js');
const autoUnban = require('./functions/moderation/autoUnban.js');
const autoUnmute = require('./functions/moderation/autoUnmute.js');
const bumpReminder = require('./functions/bump/bumpReminder.js');
autoUnban(client, db);
autoUnmute(client, db);
bumpReminder(client, db);

client.commands = new Collection();
const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath);

for (const folder of commandFolders) {
    const commandsPath = path.join(foldersPath, folder);
    const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
    for (const file of commandFiles) {
        const filePath = path.join(commandsPath, file);
        try {
            const command = require(filePath);
            if ('data' in command && 'execute' in command) {
                client.commands.set(command.data.name, command);
            } else {
                console.warn(chalk.yellow(`⚠️  La commande à ${filePath} manque une propriété requise "data" ou "execute".`));
            }
        } catch (error) {
            console.error(chalk.red(`❌ Erreur lors du chargement de la commande à ${filePath}:`), error);
        }
    }
}

const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));

for (const file of eventFiles) {
    const filePath = path.join(eventsPath, file);
    try {
        const event = require(filePath);
        if (event.once) {
            client.once(event.name, (...args) => event.execute(...args));
        } else {
            client.on(event.name, (...args) => event.execute(...args));
        }
    } catch (error) {
        console.error(chalk.red(`❌ Erreur lors du chargement de l'événement à ${filePath}:`), error);
    }
}

client.login(token).catch(err => {
    console.error(chalk.red('❌ Erreur lors de la connexion:'), err);
    process.exit(1);
});