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

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

client.commands = new Collection();
const commandFiles = fs.readdirSync("./commands").filter(file => file.endsWith(".js"));

for (const file of commandFiles) {
	const command = require(`./commands/${file}`);
	// Set a new item in the Collection
	// With the key as the command name and the value as the exported module
	client.commands.set(command.data.name, command);
}

client.on("interactionCreate", async interaction => {
	if (!interaction.isCommand()) return;

	const command = client.commands.get(interaction.commandName);

	if (!command) return;

	try {
		// Show "Bot is thinking..."
		await interaction.deferReply();
		await command.execute(interaction);
	} catch (error) {
		console.error(error);
		if (interaction.replied) {
			await interaction.followUp("An unknown error occured while performing this command!");
		}
		else {
			await interaction.editReply("An unknown error occured while performing this command!");
		}
		await logError(error, interaction);
	}
});

/**
 * @param {Error} error 
 * @param {import('discord.js').ChatInputCommandInteraction} interaction
 */
async function logError(error, interaction) {
	const logChannel = client.channels.cache.get(logChannelId);
	if (!logChannel) {
		console.log("Couldn't find log channel with the given id: " + logChannelId);
		return;
	}
	
	const message = await interaction.fetchReply();
	let errMsg = `An error occured when performing \`/${interaction.commandName}\` (${interaction.options.data.map((option) => `${option.name}: \`${option.value}\``).join(", ")}) at ${message.url}\n`;
	errMsg += `\`\`\`\n${error.stack ? error.stack : error}\n\`\`\``;

	await logChannel.send(errMsg);
}

client.on("error", async error => {
	console.error(error);
});

client.once("ready", () => {
    console.log("Ready");
	client.user.setActivity({
		name: "use /take and /submit",
		type: ActivityType.Custom
	});
});

client.login(token);