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

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 interaction.deferReply({ flags: MessageFlags.Ephemeral });

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

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

            await interaction.editReply({ content: "Message sent successfully!" });
        } catch (error) {
            console.error("Webhook error:", error);
            await interaction.editReply({
                embeds: [createErrorEmbed("Failed to send message via webhook. Ensure the bot has 'Manage Webhooks' permission and the payload is valid.", "Delivery Failed")]
            });
        }
    }
});
