import { describe, test, expect, beforeAll, afterEach, setDefaultTimeout } from "bun:test"
import { spike, spikeRepo } from "./setup"
import { type TestPR, expectPullRequestWebhook, openTestPR, cleanupTestPR } from "./helpers"
import { handleGiteaWebhook } from "../src/bridge"
import { client, startDiscord } from "../src/discord"

setDefaultTimeout(30_000)

beforeAll(async () => {
  await startDiscord()
})

const prsToCleanup: TestPR[] = []
afterEach(async () => {
  while (prsToCleanup.length) {
    await cleanupTestPR(prsToCleanup.pop()!)
  }
})

describe("bridge: Spike-owned repo", () => {
  test("Spike creating a PR on their own repo creates a Discord thread", async () => {
    const branch = `test-${crypto.randomUUID().slice(0, 8)}-bridge`

    await expectPullRequestWebhook({ action: "opened", branch }, async (webhook) => {
      const pr = await openTestPR(spikeRepo, spike, branch)
      prsToCleanup.push(pr)
      const payload = await webhook

      // Process the webhook through the bridge (Gitea → Discord)
      await handleGiteaWebhook(payload, "pull_request")

      // Verify a Discord thread was created
      const channelId = (await import("../src/config")).getConfig("channelId")
      const channel = await client.channels.fetch(channelId)
      if (!channel || !("threads" in channel)) throw new Error("Could not fetch channel")

      const threads = await channel.threads.fetchActive()
      const thread = threads.threads.find((t) => t.name.includes(branch))
      expect(thread).toBeDefined()
    })
  })
})
