import {data} from "../wwwroot/core/appData.js";
import {launchWorker} from "../wwwroot/core/namecards/workerLauncher.js";
import {AttachmentBuilder} from "discord.js";
import {Logger} from "../wwwroot/core/logging/logger.js";

data.client.on('clientReady', async () => {
    console.log("Ready!");

    const guild = await data.client.guilds.fetch(data.testGuildID);
    const member = await guild.members.fetch(data.testUserID);

    console.log("Emitting fake guildMemberAdd...");
    data.client.emit("guildMemberAdd", member);
});

data.client.on('guildMemberAdd', async (member) => {
    try {
        const avatarUrl = member.user.displayAvatarURL({ extension: 'png', size: 512 });
        const username = member.displayName || member.user.username;

        const result = await launchWorker({
            templatePath: data.nameCardTemplate,
            avatarURL: avatarUrl,
            username: username,
        });

        const attachment = new AttachmentBuilder(Buffer.from(result.result), { name: 'namecard.png' });
        /*const attachment = new AttachmentBuilder(
            Buffer.isBuffer(result.result) ? result.result : Buffer.from(result.result),
            { name: 'namecard.png' }
        );*/

        const channel = await member.guild.channels.fetch(data.welcomeChannelID);
        await channel.send({ files: [attachment] });

    } catch (err) {
        await Logger.error('Failed to generate/send name card:', err);
    }
});

await data.client.login(process.env.DISCORD_TOKEN);
