import { ensure } from "@workshop/shared/utils"
import {
  Client,
  type CacheType,
  type ChatInputCommandInteraction,
  type Interaction,
  type SlashCommandOptionsOnlyBuilder,
} from "discord.js"

export const runCommand = async (interaction: Interaction<CacheType>) => {
  if (!interaction.isChatInputCommand()) return

  const command = commands.find((cmd) => cmd.command.name === interaction.commandName)
  ensure(command, `Command ${interaction.commandName} not found`)

  try {
    await command.execute(interaction)
  } catch (error) {
    const content = `❌ Error executing command ${interaction.commandName}: ${
      error instanceof Error ? error.message : String(error)
    }`
    console.error(content)
    if (interaction.deferred) {
      await interaction.editReply({ content })
    } else {
      await interaction.reply({ content, ephemeral: true })
    }
  }
}

export const registerCommands = async (client: Client<boolean>) => {
  const commandList = commands.map((cmd) => cmd.command)
  await client.application!.commands.set(commandList)
}

type ExecuteCommandFunction = (interaction: ChatInputCommandInteraction) => Promise<void>
const commands: { command: SlashCommandOptionsOnlyBuilder; execute: ExecuteCommandFunction }[] = []
