import { ChatInputCommandInteraction, Message } from "discord.js";

export default {
  data: {
    name: "eval",
    description: "Chạy mã JavaScript (chỉ chủ bot).",
    toJSON() {
      return {
        name: "eval",
        description: "Chạy mã JavaScript (chỉ chủ bot).",
      };
    },
  },
  ownersOnly: true,
  async execute(input: ChatInputCommandInteraction | Message, args?: string[]) {
    const code = args?.join(" ");
    if (!code) {
      return input instanceof Message
        ? input.reply("❌ Không có code để chạy.")
        : input.reply({ content: "❌ Không có code để chạy.", ephemeral: true });
    }

    try {
      let result = eval(code);
      if (result instanceof Promise) result = await result;

      const output = typeof result === "object" ? JSON.stringify(result, null, 2) : result;

      if (input instanceof Message) {
        await input.reply(`✅ Output:\n\`\`\`js\n${output}\n\`\`\``);
      } else {
        await input.reply({ content: `✅ Output:\n\`\`\`js\n${output}\n\`\`\``, ephemeral: true });
      }
    } catch (err) {
      if (input instanceof Message) {
        await input.reply(`❌ Error:\n\`\`\`${err}\`\`\``);
      } else {
        await input.reply({ content: `❌ Error:\n\`\`\`${err}\`\`\``, ephemeral: true });
      }
    }
  },
};