import { expect } from "e2e";
import { test, WEB, makeState, runPromise } from "./t3.ts";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
import { join } from "node:path";

test("Repository group defaults to its registered root checkout", WEB, async ({t3, app, screen, browser}) => {
  const parent = await mkdtemp(join(T3_HOME, "group-fixture-"));
  const root = join(parent, "group-root-demo");
  for (const sub of ["_archive/old-tool", "app-a", "app-b"]) {
    await mkdir(join(root, sub), {recursive:true});
    await writeFile(join(root, sub, "readme.txt"), sub);
  }
  const git = (args: string[]) => runPromise(run("git", args, {cwd:root}));
  await git(["init", "--quiet", "--initial-branch=main"]);
  await git(["add", "."]);
  await git(["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-qm", "Initial"]);
  await git(["remote", "add", "origin", "https://github.com/example/group-root-demo.git"]);
  const state = makeState(T3_HOME);
  for (const sub of ["_archive/old-tool", "app-a", "app-b", ""]) {
    await runPromise(state.cli(["project", "add", sub ? `${root}/${sub}` : root, "--title", sub ? sub.split("/").at(-1)! : "group-root-demo"]));
  }
  await t3.open("/pull-requests");
  await screen.getByRole("combobox", "Filter threads by project", {exact:true}).tap();
  await screen.getByRole("option").filter({hasText:"group-root-demo"}).tap();
  await screen.getByRole("button", "New thread").first().tap();
  await app.screenshot("group-new-thread-checkout");
  const selectedProject = await browser.evaluate(() => document.querySelector("[data-draft-project-trigger]")?.textContent ?? "");
  await screen.getByRole("textbox").fill("Confirm the selected checkout");
  await screen.getByRole("textbox").press("Enter");
  await screen.getByText("This turn is a replay.", {exact:false}).waitFor();
  await app.screenshot("created-thread-checkout");
  await expect(selectedProject).toBe("group-root-demo");
});
