const { Client, Collection, Events, GatewayIntentBits } = require('discord.js');
const { updateCommands } = require("./updateCommands");
const { token } = require('./config.json');
const fs = require('node:fs');
const path = require('node:path');

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


/** REGISTER COMMANDS **/
client.commands = new Collection();
const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath);

for (const folder of commandFolders) {
  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 command = require(filePath);
    if ('data' in command && 'execute' in command) {
      client.commands.set(command.data.name, command);
    } else {
      console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
    }
  }
}

/** SLASH COMMAND HANDLER **/
client.on(Events.InteractionCreate, async interaction => {
	if (interaction.isChatInputCommand()) {
	  const command = client.commands.get(interaction.commandName);
	  if (command) {
		try {
		  await command.execute(interaction);
		} catch (error) {
		  console.error(error);
  
		  if (!(interaction.replied || interaction.deferred)) {
			await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
		  }
		}
	  } else {
		console.error(`No command matching ${interaction.commandName} was found.`);
	  }
	}
  });

/** READY SEQUENCE **/
client.once(Events.ClientReady, c => {
  console.log(`Ready! Logged in as ${c.user.tag}`);
});

client.login(token);