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

const launch = async () => {
    try{

        data.instagramTokenManager.startWatching();

        //data.tiktokTokenManager.startWatching();

        data.instagramPoller.on("newPost", async ({permalink, userId}) => {
            const modified = JsonManager.upsertPost("./posts.json", {permalink, userId})
            if(!modified) return;

            const message = `Behold ! Some new awesome content has been posted ! \n\n${permalink}`;
            await data.sender.send(data.socialChannelID, message)
        });

        data.client.once('clientReady', async () => {
            await data.sender.send(data.updateChannelID, "I'm now online ! ✅")
            console.log(`✅ Logged in as ${data.client.user.tag}`);
        });

        data.client.on('messageCreate', async (message) => {
            const isGuildOwner = message.guild && message.author.id === message.guild.ownerId;
            if (message.content === '/login' && isGuildOwner) {
                await message.reply(data.instagramTokenManager.getOauthUrl());
            }
        });

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

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

                const attachment = new AttachmentBuilder(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);
            }
        });

        process.on('SIGINT', async () => {
            try {
                await data.sender.send(data.updateChannelID, "I'm shutting down, now. Bye! 👋")
            } catch (error) {
                await Logger.error("Error while shutting down", error);
            } finally {
                await data.client.destroy();
                process.exit(0);
            }
        });

        await data.client.login(process.env.DISCORD_TOKEN);
        data.instagramPoller.start(600000);

    } catch(err){
        await Logger.error("Unexpected error", err)
    }
}

export {launch}
