/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Dismissing a real worktree checkout releases a fresh draft send", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Checkout review", {
    "t3.json": JSON.stringify({ defaultThreadEnvMode: "local" }),
  });
  await runPromise(run("git", ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"], { cwd: project }));
  const thread = await t3.thread({ project, title: "Review preparation", messages: ["Ready for review"], model: "multi-turn" });
  await t3.open(thread);
  const projectId = await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl);
    const snapshot = yield* client["orchestration.subscribeShell"]({}).pipe(Stream.runHead);
    if (snapshot._tag !== "Some" || snapshot.value.kind !== "snapshot") throw new Error("No project snapshot");
    return snapshot.value.snapshot.projects.find((entry) => entry.workspaceRoot === project)!.id;
  }).pipe(Effect.scoped));
  await t3.open(`/pull-requests?selectedProjectId=${projectId}&repository=pingdotgg/t3code&number=48625`);
  await screen.getByRole("button", "Check out", { exact: true }).tap();
  await screen.getByRole("menuitem", /In a separate worktree/).tap();
  await screen.getByText("Preparing the pull request checkout...", { exact: true }).waitFor();
  await screen.getByRole("button", "Dismiss notification", { exact: true }).tap();
  const composer = screen.getByRole("textbox");
  await composer.fill("Explain this checkout dismissal");
  await composer.press("Enter");
  try {
    await expect(browser.locator("[data-draft-project-trigger]")).not.toBeVisible({ timeout: 12000 });
  } finally {
    await app.screenshot("fresh-send-after-toast-dismissal");
  }
});
