const fs = require('fs');
const { Client } = require('discord.js');
const chalk = require('chalk');

const tokens = fs.readFileSync('token.txt', 'utf8').split('\n').map(token => token.trim()).filter(Boolean);
const rawMembers = fs.readFileSync('members.txt', 'utf8').split('\n').map(id => id.trim());
const config = JSON.parse(fs.readFileSync('config.json', 'utf8'));

const clients = tokens.map(token => new Client({ intents: 3276799 }));
let globalCounter = 0;
let globalFailedCounter = 0;

const colors = [
    chalk.greenBright,
    chalk.blueBright,
    chalk.cyanBright,
    chalk.magentaBright,
    chalk.yellowBright,
    chalk.redBright,
    chalk.whiteBright
];

function getRandomColor() {
    return colors[Math.floor(Math.random() * colors.length)];
}

function distributeMembers(rawMembers) {
    const memberChunks = [];
    let currentChunk = [];

    rawMembers.forEach(line => {
        if (line === '----------') {
            memberChunks.push(currentChunk);
            currentChunk = [];
        } else if (line) {
            currentChunk.push(line);
        }
    });

    if (currentChunk.length > 0) {
        memberChunks.push(currentChunk);
    }

    return memberChunks;
}

const membersChunks = distributeMembers(rawMembers);

async function startClients() {
    clients.forEach((client, i) => {
        loginAndSendDMs(client, i);
    });
}

async function loginAndSendDMs(client, i) {
    try {
        await client.login(tokens[i]);
        console.log(getRandomColor()(`Bot ${i + 1} connecté`));

        if (membersChunks[i]) {
            sendDMs(client, membersChunks[i], i);
        } else {
            console.log(getRandomColor()(`Aucun membres assignés au bot ${i + 1}`));
        }
    } catch (error) {
        console.error(chalk.redBright(`Erreur lors de la connexion du bot ${i + 1}:`), error);
    }
}

async function sendDMs(client, memberChunk, botIndex) {
    memberChunk.forEach(userId => {
        sendDM(client, userId, botIndex);
    });
    console.log(getRandomColor()(`Bot ${botIndex + 1} a commencé à DM.`));
}

async function sendDM(client, userId, botIndex) {
    try {
        const user = await client.users.fetch(userId);
        const messageContent = getMessageContent(user);
        await user.send(messageContent);
        globalCounter++;
        console.log(getRandomColor()(`[+] --> ${user.tag} | ${globalCounter} | par le bot ${botIndex + 1}`));
    } catch (error) {
        globalFailedCounter++;
        console.log(chalk.redBright(`FAILED DM ${userId} | ${globalFailedCounter} | par le bot ${botIndex + 1}`));
    }
}

function getMessageContent(user) {
    const baseMessage = config.message;
    return baseMessage.replace("{user}", user ? `<@${user.id}>` : "");
}

startClients();