import { getConfig } from "../config"
import { assertNever } from "@workshop/shared/utils"
import type { Gitea } from "./types"

export function convertUsername(opts: { discordUsername: string } | { giteaUsername: string }): string {
  const giteaToDiscordUserMappings = getConfig("giteaToDiscordUserMappings")
  let convertedUsername: string | undefined
  let username: string
  if ("giteaUsername" in opts) {
    username = opts.giteaUsername
    convertedUsername = giteaToDiscordUserMappings[username]
  } else {
    username = opts.discordUsername
    const entries = Object.entries(giteaToDiscordUserMappings)
    const result = entries.find(([_, discordUsername]) => discordUsername === username)
    if (result) convertedUsername = result[0]
  }

  return convertedUsername || `💥${username}💥`
}

type PullRequestState = "closed" | "merged" | "opened"
function prState(pullRequest: Gitea.PullRequest): { icon: string; label: string } {
  let state: PullRequestState = "opened"
  if (pullRequest.merged) {
    state = "merged"
  } else if (pullRequest.state === "closed") {
    state = "closed"
  }

  let stateInfo: { icon: string; label: string }
  if (state === "merged") {
    stateInfo = { icon: "🟣", label: "merged" }
  } else if (state === "closed") {
    stateInfo = { icon: "🔴", label: "closed" }
  } else if (state === "opened") {
    stateInfo = { icon: "🟢", label: "opened" }
  } else {
    assertNever(state, `Unhandled pull request state: ${state}`)
  }
  return stateInfo
}

export function threadName(pullRequest: Gitea.PullRequest, repository: Gitea.Repository): string {
  const stateInfo = prState(pullRequest)
  const name = `${stateInfo.icon} [${repository.name}] ${pullRequest.title}`
  return name.slice(0, 100)
}
