import { createCommand } from "@shared/lib/utils";
import { SlashCommandBuilder, PermissionFlagsBits, MessageFlags } from "discord.js";
import { createErrorEmbed } from "@/lib/embeds";
import { sendWebhookMessage } from "@/lib/webhookUtils";
import { withCommandErrorHandling } from "@lib/commandUtils";

export const webhook = createCommand({
    data: new SlashCommandBuilder()
        .setName("webhook")
        .setDescription("Send a message via webhook using a JSON payload")
        .setDefaultMemberPermissions(PermissionFlagsBits.ManageWebhooks)
        .addStringOption(option =>
            option.setName("payload")
                .setDescription("The JSON payload for the webhook message")
                .setRequired(true)
        ),
    execute: async (interaction) => {
        await withCommandErrorHandling(
            interaction,
            async () => {
                const payloadString = interaction.options.getString("payload", true);
                let payload;

                try {
                    payload = JSON.parse(payloadString);
                } catch (error) {
                    await interaction.editReply({
                        embeds: [createErrorEmbed("The provided payload is not valid JSON.", "Invalid JSON")]
                    });
                    return;
                }

                const channel = interaction.channel;

                if (!channel || !('createWebhook' in channel)) {
                    await interaction.editReply({
                        embeds: [createErrorEmbed("This channel does not support webhooks.", "Unsupported Channel")]
                    });
                    return;
                }

                await sendWebhookMessage(
                    channel,
                    payload,
                    interaction.client.user,
                    `Proxy message requested by ${interaction.user.tag}`
                );

                await interaction.editReply({ content: "Message sent successfully!" });
            },
            { ephemeral: true }
        );
    }
});
