import { expect } from "e2e";
import { writeFile, chmod } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Create MR never opens another branch's request after checkout switches", WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project("checkout-switch-demo");
  const git = (...args: string[]) => runPromise(run("git", args, {cwd: project}));
  const glab = (...args: string[]) => runPromise(run("glab", args, {cwd: project}));
  const name = `t3-proof-47532-${randomUUID().slice(0,8)}`;
  const created = JSON.parse((await glab("api", "-X", "POST", "projects", "-f", `name=${name}`, "-f", "visibility=private")).stdout);
  try {
    await git("config", "user.name", "Scenario");
    await git("config", "user.email", "scenario@example.invalid");
    await git("config", "core.hooksPath", ".git/hooks");
    await git("remote", "add", "origin", created.http_url_to_repo);
    await git("push", "-u", "origin", "main");
    await git("remote", "set-head", "origin", "main");
    await git("switch", "-c", "other");
    await git("commit", "--allow-empty", "-m", "Other branch work");
    await git("push", "-u", "origin", "other");
    const mr = JSON.parse((await glab("api", "-X", "POST", `projects/${created.id}/merge_requests`, "-f", "source_branch=other", "-f", "target_branch=main", "-f", "title=Other branch work")).stdout);
    await git("switch", "-c", "feature", "main");
    await git("push", "-u", "origin", "feature");
    await git("commit", "--allow-empty", "-m", "Feature work");
    const remote = `${project}-push.git`;
    await git("clone", "--bare", created.http_url_to_repo, remote);
    await git("remote", "set-url", "--push", "origin", remote);
    const input = {project, title: "Feature work", messages: ["Start"]};
    const thread = await t3.thread({...input, model: "default"}).catch((error: unknown) => {
      if (!String(error).includes("Model default is not advertised by provider devReplay.")) throw error;
      return t3.thread(input);
    });
    await writeFile(`${project}/.git/hooks/pre-push`, "#!/bin/sh\ngit switch --quiet other\n");
    await chmod(`${project}/.git/hooks/pre-push`, 0o755);
    await t3.open(thread);
    await browser.evaluate(() => {
      const style = document.createElement("style");
      style.textContent = "*, *::before, *::after { animation-duration: 0s !important; transition-duration: 0s !important; }";
      document.head.append(style);
    });
    await screen.getByRole("button", "Git action options").tap();
    await screen.getByRole("menuitem", "Create MR", {exact: true}).tap();
    await screen.getByText(new RegExp(`^Opened MR #${mr.iid}$|^Created MR$|^Action failed$`)).waitFor();
    await app.screenshot("merge-request-after-checkout-switch");
    expect(await screen.getByText(`Opened MR #${mr.iid}`, {exact: true}).isVisible()).toBe(false);
    await screen.getByText(/feature is no longer checked out/).waitFor();
    expect((await git("branch", "--show-current")).stdout.trim()).toBe("other");
    expect((await git("--git-dir", remote, "rev-parse", "feature")).stdout.trim()).toBe((await git("rev-parse", "feature")).stdout.trim());
  } finally {
    await glab("api", "-X", "DELETE", `projects/${created.id}`);
  }
});
