import { Events } from "discord.js"
import type { Interaction } from "discord.js"
import commands from "@/commands"
import buttons, { buttonFolders } from "@/buttons"
import selectMenus from "@/selectmenus"
import { playerEdit } from "@/utils/player"
import { logConsole, logConsoleError } from "@/utils/console"

export const name = Events.InteractionCreate
export async function execute(interaction: Interaction) {
	if (interaction.isChatInputCommand()) {
		const chatInputCommand = commands.find(cmd => cmd.data.name == interaction.commandName)
		if (!chatInputCommand) { logConsole('discordjs', 'interaction_create.command_not_found', { command: interaction.commandName }); return }

		logConsole('discordjs', 'interaction_create.command_launched', { command: interaction.commandName, user: interaction.user.tag })

		try { await chatInputCommand.execute(interaction) }
		catch (error) { logConsoleError('discordjs', 'interaction_create.command_error', { command: interaction.commandName }, error as Error) }
	}
	else if (interaction.isAutocomplete()) {
		const autocompleteRun = commands.find(cmd => cmd.data.name == interaction.commandName)
		if (!autocompleteRun?.autocompleteRun) { logConsole('discordjs', 'interaction_create.autocomplete_not_found', { command: interaction.commandName }); return }

		logConsole('discordjs', 'interaction_create.autocomplete_launched', { command: interaction.commandName, user: interaction.user.tag })

		try { await autocompleteRun.autocompleteRun(interaction) }
		catch (error) { logConsoleError('discordjs', 'interaction_create.autocomplete_error', { command: interaction.commandName }, error as Error) }
	}
	else if (interaction.isButton()) {
		const button = buttons.find(btn => btn.id === interaction.customId)
		if (!button) { logConsole('discordjs', 'interaction_create.button_not_found', { id: interaction.customId }); return }

		logConsole('discordjs', 'interaction_create.button_clicked', { id: interaction.customId, user: interaction.user.tag })

		try { await button.execute(interaction) }
		catch (error) { logConsoleError('discordjs', 'interaction_create.button_error', { id: interaction.customId }, error as Error) }

		if (buttonFolders.find(folder => folder.name === "player" ? folder.commands.some(cmd => cmd.id === interaction.customId) : false)) await playerEdit(interaction)
	}
	else if (interaction.isAnySelectMenu()) {
		const selectMenu = selectMenus.find(menu => menu.id === interaction.customId)
		if (!selectMenu) { logConsole('discordjs', 'interaction_create.selectmenu_not_found', { id: interaction.customId }); return }

		logConsole('discordjs', 'interaction_create.selectmenu_used', { id: interaction.customId, user: interaction.user.tag })

		try { await selectMenu.execute(interaction) }
		catch (error) { logConsoleError('discordjs', 'interaction_create.selectmenu_error', { id: interaction.customId }, error as Error) }
	}
}
