import { Logger } from './wwwroot/core/logging/logger.js';
import JsonManager from './wwwroot/core/utils/jsonManager.js';
import { data } from "./wwwroot/core/appData.js";

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', (message) => {
        const isGuildOwner = message.guild && message.author.id === message.guild.ownerId;
        if (message.content === '/login' && isGuildOwner) {
            message.reply(data.instagramTokenManager.getOauthUrl());
        }
    });

    data.client.on('guildMemberAdd', member => {
        const avatar = member.user.avatarURL();
    });

    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)
}
