// js-src/ping/index.js - Ping Command Handler and Definition for Extism
// --- Command Definition ---

// Define the structure for the /ping command
// This structure should mirror the fields of discordgo.ApplicationCommand
// See: https://pkg.go.dev/github.com/bwmarrin/discordgo@v0.28.1#ApplicationCommand
const pingCommandDefinition = {
  // Name must match the filename (ping.wasm -> "ping") and the desired slash command
  Name: "ping",
  // Description is shown to the user in Discord
  Description: "Checks the bot's responsiveness (handled by Wasm!)",
  // Options would be an array of ApplicationCommandOption objects if the command took arguments
  Options: [],
  // Add other fields like DefaultMemberPermissions if needed
  // DefaultMemberPermissions: String(1 << 5), // Example: Send Messages permission as string
  // DMPermission: true, // Example: Allow command in DMs
};

// Exported function to provide the command definition
function get_command_definition() {
  try {
    // Convert the definition object to a JSON string
    const jsonDefinition = JSON.stringify(pingCommandDefinition);
    // Output the JSON string for the Go host
    Host.outputString(jsonDefinition);
    return 0; // Success
  } catch (e) {
    // Log error if something goes wrong during stringification
    console.error("Error stringifying command definition:", e);
    Host.outputString(`{"error": "Failed to generate command definition: ${e.message}"}`);
    return 1; // Indicate failure
  }
}

// --- Interaction Handler (Remains the same) ---

// Exported function to handle the interaction at runtime
function handle_interaction() {
  try {
    // const inputJson = Host.inputString(); // Input still available if needed
    // console.log("Ping plugin received interaction");

    const response = {
      content: "Pong!",
      ephemeral: false,
    };
    const jsonResponse = JSON.stringify(response);
    Host.outputString(jsonResponse);
    return 0; // Success
  } catch (e) {
    console.error("Error handling interaction:", e);
    Host.outputString(`{"error": "Failed to handle interaction: ${e.message}"}`);
    return 1; // Indicate failure
  }
}

// --- Exports ---

// Export both functions so the Extism runtime can call them
module.exports = {
  get_command_definition, // Function for registration
  handle_interaction,    // Function for runtime execution
};