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

test("Remote names containing slashes preserve branch names and reject collisions", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("branch-demo");
  const git = async (...args: string[]) => (await runPromise(run("git", args, {cwd: project}))).stdout.trim();
  await git("clone", "--bare", ".", "../remote.git");
  await git("--git-dir=../remote.git", "branch", "feature/demo");
  await git("--git-dir=../remote.git", "branch", "conflict");
  await git("remote", "add", "team/origin", "../remote.git");
  await git("fetch", "team/origin");
  const thread = await t3.thread({project, title: "Remote branch demonstration", messages: ["Ready"]});
  await browser.addInitScript(() => {
    const ids = new Set<string>();
    const watched = new WeakSet<WebSocket>();
    let completed = 0;
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if (typeof data === "string") for (const msg of [JSON.parse(data)].flat()) if(msg.tag === "vcs.switchRef") ids.add(String(msg.id));
      if (!watched.has(this)) {
        watched.add(this);
        this.addEventListener("message", event => {
          if(typeof event.data !== "string") return;
          for(const msg of [JSON.parse(event.data)].flat()) if(msg._tag === "Exit" && ids.delete(String(msg.requestId))) {
            document.documentElement.dataset.switchCompleted = String(++completed);
            document.documentElement.dataset.switchResult = JSON.stringify(msg.exit);
          }
        });
      }
      return send.call(this,data);
    };
  });
  await browser.setViewport({width:1280,height:800});
  await t3.open(thread);
  const picker = browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').first();
  const select = async (name: string, count: number) => {
    await picker.click();
    await screen.getByRole("option", new RegExp(`^${name.replaceAll("/", "/\\s*")}\\b`)).click();
    await browser.locator(`html[data-switch-completed="${count}"]`).waitFor({state:"attached"});
  };
  await select("team/origin/feature/demo", 1);
  const created = await git("branch", "--show-current");
  const upstream = await git("rev-parse", "--symbolic-full-name", "@{upstream}");
  await app.screenshot("selected-remote-feature");
  await select("main", 2);
  await git("branch", "conflict");
  // Reload the app to read the newly created local collision branch.
  await t3.open(thread);
  await select("team/origin/conflict", 1);
  const collisionBranch = await git("branch", "--show-current");
  const collisionReply = await browser.evaluate(() => document.documentElement.dataset.switchResult ?? "");
  if (collisionReply.includes("branch_already_exists")) {
    await screen.getByText("Failed to switch ref.", {exact: true}).waitFor();
    await browser.evaluate(async () => {
      await Promise.all(document.getAnimations().filter(animation => animation.effect?.getComputedTiming().iterations !== Infinity).map(animation => animation.finished.catch(() => {})));
    });
  }
  await app.screenshot("remote-branch-collision");
  expect({created, upstream, collisionBranch, rejected: collisionReply.includes("branch_already_exists")}).toEqual({
    created:"feature/demo", upstream:"refs/remotes/team/origin/feature/demo", collisionBranch:"main", rejected:true,
  });
});
