import { Client, Collection, GatewayIntentBits } from "discord.js";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { config } from "./src/config.js";
import { MusicQueue } from "./src/music/queue.js";
import { startWebServer } from "./src/web/server.js";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const client = new Client({
  intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates],
});

client.commands = new Collection();
const foldersPath = path.join(__dirname, "src/commands");
const commandFolders = fs.readdirSync(foldersPath);

for (const folder of commandFolders) {
  if (folder.indexOf("[disabled]") === -1 || config.environnement === "test") {
    const commandsPath = path.join(foldersPath, folder);
    const commandFiles = fs
      .readdirSync(commandsPath)
      .filter((file) => file.endsWith(".js"));
    for (const file of commandFiles) {
      const filePath = path.join(commandsPath, file);
      const commandFile = await import(filePath);
      if ("data" in commandFile.command && "execute" in commandFile.command) {
        client.commands.set(commandFile.command.data.name, commandFile);
      } else {
        console.log(
          `[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`
        );
      }
    }
  }
}

const eventsPath = path.join(__dirname, "src/events");
const eventFiles = fs
  .readdirSync(eventsPath)
  .filter((file) => file.endsWith(".js"));

for (const file of eventFiles) {
  const filePath = path.join(eventsPath, file);
  const eventFile = await import(filePath);
  if (eventFile.event.once) {
    client.once(eventFile.event.name, (...args) =>
      eventFile.event.execute(...args)
    );
  } else {
    client.on(eventFile.event.name, (...args) =>
      eventFile.event.execute(...args)
    );
  }
}

client.login(config.token);

const musicQueue = new MusicQueue(client);
startWebServer({ queue: musicQueue });

export { client, musicQueue };
