import { ActivityType, type Client } from "discord.js"
import { runCommand } from "./commands"
import { createPRComment, convertDiscordMentionsToGitea, getPRByDiscordThreadId } from "../bridge"
import { convertUsername } from "../gitea"

export const listenForEvents = (client: Client) => {
  client.on("interactionCreate", async (interaction) => {
    return runCommand(interaction)
  })

  client.on("messageCreate", async (msg) => {
    if (msg.author.bot) return

    try {
      // Check if this is a PR thread
      const prData = getPRByDiscordThreadId(msg.channel.id)
      if (prData) {
        const username = convertUsername({ discordUsername: msg.author.displayName })
        const messageContent = await convertDiscordMentionsToGitea(msg.content)
        const message = `**${username}**: ${messageContent}`
        await createPRComment(prData, message, msg.id)
      }

      // if it is a dm always respond
      // if it is a guild message, only respond if the bot is at mentioned
      if (!msg.guild || msg.mentions.has(client.user!)) {
        // Do nothing right now
        // await msg.channel.send(`You said: ${msg.content}`)
      }
    } catch (error) {
      console.error("Error handling messageCreate event:", error)
      msg.channel.send("An error occurred 💥.")
    }
  })

  client.on("ready", () => {
    // set the bots description
    const branch = process.env.RENDER_GIT_BRANCH || "unknown"
    const commit = process.env.RENDER_GIT_COMMIT?.slice(0, 7) || "deadbeef"
    client.user?.client.user?.setActivity(`${branch}@${commit}`, {
      type: ActivityType.Playing,
      state: `Error Count: ${0}`,
      url: `https://github.com/${process.env.RENDER_GIT_REPO_SLUG}/commit/${commit}`,
    })
  })

  client.on("error", (error) => {
    console.error("Discord client error:", error)
  })

  client.on("warn", (info) => {
    console.warn("Discord client warning:", info)
  })
}
