import { expect } from "e2e";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Reused PR worktree rejects an unrelated nested upstream", WEB, async ({ t3, app, browser, screen }) => {
 const project = await t3.project("PR upstream proof", { "t3.json": JSON.stringify({ defaultThreadEnvMode: "local" }) });
 const git = (...args: string[]) => runPromise(run("git", args, { cwd: project }));
 await git("fetch", process.env.PROOF_SEED!, "+refs/heads/*:refs/remotes/seed/*", "refs/tags/original-a:refs/tags/original-a");
 await git("remote", "add", "origin", "https://t3code-factory-test@dev.azure.com/t3code-factory-test/t3-factory-test/_git/proof-47799-evidence-1");
 await git("config", "credential.helper", '!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f');
 await git("update-ref", "refs/remotes/origin/fix", "refs/remotes/seed/cached-b");
 await git("update-ref", "refs/remotes/origin/release/fix", "refs/remotes/seed/release/fix");
 await git("branch", "fix", "original-a");
 const worktree = `${project}-existing-worktree`;
 await git("worktree", "add", worktree, "fix");
 await git("config", "branch.fix.remote", "origin");
 await git("config", "branch.fix.merge", "refs/heads/release/fix");
 const original = (await git("rev-parse", "original-a")).stdout.trim();
 await t3.thread({ project, title: "PR checkout proof", messages: ["Ready"] });
 await t3.open("/");
 await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').first().click();
 await screen.getByPlaceholder("Search refs...").fill("#630");
 const checkout = /Checkout (?:merge|pull|change) request/i;
 await screen.getByRole("option", checkout).tap();
 const dialog = screen.getByRole("dialog", checkout);
 await dialog.getByText("Repro PR from fix", { exact: true }).waitFor();
 await dialog.getByRole("button", "Worktree", { exact: true }).tap();
 await dialog.waitFor({ state: "hidden" });
 await app.screenshot("reused-pr-worktree-checkout");
 const head = (await git("-C", worktree, "rev-parse", "HEAD")).stdout.trim();
 expect(head).toBe(original);
 await expect(screen.getByText("Checked out, but not confirmed on the latest commit", { exact: false })).toBeVisible();
});
