import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import { CommandId, ThreadId } from "@t3tools/contracts";
import { execFileSync } from "node:child_process";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as Effect from "effect/Effect";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

const uuid = Effect.flatMap(SecureRandom.SecureRandom, r => r.uuidV4());
test("Explicitly unlinked branch pull request stays absent", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Unlink demonstration");
  execFileSync("git", ["checkout", "-b", "factory/issue-46638"], { cwd: project });
  const thread = await t3.thread({ project, title: "Branch pull request unlink", model: "default", messages: ["Start"] });
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    const threadId = ThreadId.make(thread.threadId);
    const { thread: state } = yield* client["orchestration.getThreadProjection"]({ threadId });
    yield* client["orchestration.dispatchCommand"]({ type: "thread.pull-request.sync", commandId: CommandId.make(yield* uuid), threadId, projectId: state.projectId, snapshotSequence: 0, expected: { workspaceRoot: project, branch: state.branch, worktreePath: state.worktreePath, linkedPullRequest: state.linkedPullRequest ?? null, branchPullRequest: state.branchPullRequest ?? null }, branchPullRequest: { projectId: state.projectId, repository: "pingdotgg/t3code", number: 46654, url: "https://github.com/pingdotgg/t3code/pull/46654" } });
    for (const number of [46654, 46644]) {
      yield* client["orchestration.dispatchCommand"]({ type: "thread.pull-request.link", commandId: CommandId.make(yield* uuid), threadId, host: "github.com", repository: "pingdotgg/t3code", number, url: `https://github.com/pingdotgg/t3code/pull/${number}`, source: "manual" });
    }
  }).pipe(Effect.scoped, Effect.provide(NodeCrypto.layer)));
  await browser.setViewport({ width: 1440, height: 1000 });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
  await screen.getByRole("button", "Linked items L", { exact: true }).tap();
  await app.screenshot("two-linked-pull-requests");
  for (const number of [46644, 46654]) {
    await screen.getByText(`#${number}`, { exact: true }).hover();
    await screen.getByRole("button", `Actions for #${number}`, { exact: true }).tap();
    await screen.getByRole("menuitem", "Unlink from thread", { exact: true }).tap();
  }
  await screen.getByText("No linked pull requests", { exact: true }).waitFor();
  await app.screenshot("after-last-unlink");
  await t3.open(thread);
  await screen.getByText("No linked pull requests", { exact: true }).waitFor();
  await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
  if (await browser.evaluate(() => document.querySelector('[aria-label="Toggle thread details panel"]')?.getAttribute("aria-pressed") !== "true")) {
    await screen.getByRole("button", "Toggle thread details panel", { exact: true }).tap();
  }
  await screen.getByRole("region", "Thread details", { exact: true }).waitFor();
  await app.screenshot("after-reload");
  const remaining = await browser.evaluate(() => [...document.querySelectorAll('a[href*="/pull/46654"]')].map(a => a.textContent));
  await screen.getByRole("combobox", "Search threads").fill("46654");
  await screen.getByRole("navigation", "Threads").getByText(/^(No threads found|Branch pull request unlink)$/).waitFor();
  await app.screenshot("search-after-unlink");
  const search = screen.getByRole("navigation", "Threads");
  await expect(search).not.toContainText("Branch pull request unlink");
  expect(remaining, "Unlinked branch PR is absent from thread details and sidebar after reload").toEqual([]);
});
