import { bus } from "../events/eventBus";
import { logger } from "../logging/logger";

export function initializeDiscordIntegrations() {
    bus.on('application.create', async (event) => {

        if (!process.env.DISCORD_APPLICATIONS_WEBHOOK) {
            logger.error("app", 'Discord Applications Webhook is not defined')
            return;
        }

        let applicantName = event.payload.member_discord_id || event.payload.member_name;
        if (event.payload.member_discord_id) {
            applicantName = `<@${event.payload.member_discord_id}>`;
        }
        const link = `${process.env.CLIENT_URL}/administration/applications/${event.payload.application}`;

        const embed = {
            title: "Application Posted",
            description: `[View Application](${link})`,
            color: 0x00ff00, // optional: green color
            timestamp: new Date().toISOString(), // <-- Discord expects ISO8601
            fields: [
                {
                    name: "Submitted By",
                    value: applicantName,
                    inline: false,
                },
            ],
        };

        // send to Discord webhook
        await fetch(process.env.DISCORD_APPLICATIONS_WEBHOOK!, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ embeds: [embed] }),
        });
    });
}
