import { describe, test, expect } from "bun:test"
import { convertUsername, threadName } from "../utils"
import type { Gitea } from "../types"

describe("convertUsername", () => {
  test("converts gitea username to discord username", () => {
    const result = convertUsername({ giteaUsername: "probablycorey" })
    expect(result).toBe("corey")
  })

  test("converts discord username to gitea username", () => {
    const result = convertUsername({ discordUsername: "corey" })
    expect(result).toBe("probablycorey")
  })

  test("returns fallback with 💥 for unknown gitea username", () => {
    const result = convertUsername({ giteaUsername: "nobody" })
    expect(result).toBe("💥nobody💥")
  })

  test("returns fallback with 💥 for unknown discord username", () => {
    const result = convertUsername({ discordUsername: "nobody" })
    expect(result).toBe("💥nobody💥")
  })
})

function fakePR(overrides: Partial<Gitea.PullRequest> = {}): Gitea.PullRequest {
  return {
    id: 1,
    number: 42,
    title: "Add feature",
    body: "",
    user: { id: 1, login: "test", full_name: "Test", avatar_url: "" },
    html_url: "",
    state: "open",
    merged: false,
    created_at: "",
    updated_at: "",
    draft: false,
    base: {},
    head: {},
    ...overrides,
  }
}

const fakeRepo: Gitea.Repository = {
  id: 1,
  name: "my-repo",
  full_name: "user/my-repo",
  owner: { id: 1, login: "user", full_name: "User", avatar_url: "" },
  html_url: "",
  private: false,
}

describe("threadName", () => {
  test("formats open PR", () => {
    const result = threadName(fakePR(), fakeRepo)
    expect(result).toBe("🟢 [my-repo] Add feature")
  })

  test("formats merged PR", () => {
    const result = threadName(fakePR({ merged: true, state: "closed" }), fakeRepo)
    expect(result).toBe("🟣 [my-repo] Add feature")
  })

  test("formats closed (not merged) PR", () => {
    const result = threadName(fakePR({ state: "closed" }), fakeRepo)
    expect(result).toBe("🔴 [my-repo] Add feature")
  })

  test("truncates to 100 characters", () => {
    const longTitle = "A".repeat(200)
    const result = threadName(fakePR({ title: longTitle }), fakeRepo)
    expect(result.length).toBe(100)
  })
})
