import { ChatInputCommandInteraction, Message } from "discord.js";
import fs from "fs";
import path from "path";
import { commands } from "../index";

export default {
  data: {
    name: "reload",
    description: "Tải lại toàn bộ lệnh từ thư mục Commands.",
    toJSON() {
      return {
        name: "reload",
        description: "Tải lại toàn bộ lệnh từ thư mục Commands.",
      };
    },
  },
  ownersOnly: true,
  async execute(input: ChatInputCommandInteraction | Message) {
    const dir = path.join(__dirname);
    const newCommands = [];

    try {
      const files = fs.readdirSync(dir).filter((file) =>
        file.endsWith(".ts") || file.endsWith(".js")
      );

      for (const file of files) {
        if (file === "reload.ts" || file === "reload.js") continue;

        const filePath = path.join(dir, file);
        delete require.cache[require.resolve(filePath)];

        const command = require(filePath).default;
        if (command) newCommands.push(command);
      }

      commands.length = 0;
      newCommands.forEach((cmd) => commands.push(cmd));

      const replyText = `✅ Đã reload ${newCommands.length} lệnh.`;

      if (input instanceof Message) {
        await input.reply(replyText);
      } else {
        await input.reply({ content: replyText, ephemeral: true });
      }
    } catch (error) {
      console.error(error);
      if (input instanceof Message) {
        await input.reply("❌ Lỗi khi reload command.");
      } else {
        await input.reply({ content: "❌ Lỗi khi reload command.", ephemeral: true });
      }
    }
  },
};