/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB, makeState, runPromise } from "./t3.ts";
import { T3_HOME } from "../e2e.config.ts";

const repository = { ".git/config": '[remote "origin"]\nurl = https://github.com/example-org/widget.git\n', "apps/web/README.md": "Web checkout" };

test("An unarchived repository group uses its open root checkout", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("clone-old", repository);
  await t3.open("/settings/projects");
  await screen.getByRole("button", "Project scope: All projects").tap();
  await screen.getByRole("menuitemradio", "clone-old", { exact: true }).tap();
  await screen.getByRole("region", "Settings content").getByRole("button", "Archive", { exact: true }).tap();
  await screen.getByRole("button", "Unarchive", { exact: true }).waitFor();
  const open = await t3.project("clone-new", repository);
  await runPromise(makeState(T3_HOME).cli(["project", "add", `${open}/apps/web`]));
  await t3.open("/settings/projects");
  const option = screen.getByRole("button", /example-org\/widget.*clone-/);
  await option.waitFor();
  try {
    await expect(option).toContainText(/clone-new$/);
  } finally {
    await browser.evaluate(() => {
      const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
      while (walker.nextNode()) {
        const node = walker.currentNode;
        if (node.textContent?.includes("/workspaces/")) node.textContent = node.textContent.replace(/\/[^\s]*\/workspaces\/w-[^/]+\//g, "/projects/");
      }
      return null;
    });
    await app.screenshot("repository-group-representative");
  }
});
