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

test("PR task checkboxes save when the marker is on the previous line", WEB, async ({ t3, app, browser, screen }) => {
  const workspace = await t3.project("Checkbox demonstration");
  const tag = `checkbox-proof-${Date.now()}`;
  const org = process.env.AZURE_DEVOPS_TEST_ORG!;
  const project = process.env.AZURE_DEVOPS_TEST_PROJECT!;
  const repository = "t3-factory-test";
  const remote = `${org}/${project}/_git/${repository}`;
  const git = (args: string[]) => runPromise(run("git", args, { cwd: workspace }));
  const az = async (args: string[]) => JSON.parse((await runPromise(run("az", [...args, "--organization", org, "-o", "json"], { cwd: workspace }))).stdout);
  await git(["remote", "add", "origin", remote]);
  const push = (ref: string) => git(["-c", 'credential.helper=!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f', "push", "--quiet", "origin", ref]);
  await push(`HEAD:refs/heads/${tag}-base`);
  await git(["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--allow-empty", "-qm", "Checkbox example"]);
  await push(`HEAD:refs/heads/${tag}-head`);
  let id: number | undefined;
  try {
    const pr = await az(["repos", "pr", "create", "--project", project, "--repository", repository, "--source-branch", `${tag}-head`, "--target-branch", `${tag}-base`, "--title", "Verify multiline task checkboxes", "--description", "-\n  [ ] Task"]);
    id = pr.pullRequestId;
    const url = `${remote}/pullrequest/${id}`;
    await browser.setViewport({ width: 1280, height: 800 });
    await browser.addInitScript(() => {
      const state = window as typeof window & { checkboxSave?: Promise<void> };
      const send = WebSocket.prototype.send;
      WebSocket.prototype.send = function(data) {
        const request = typeof data === "string" ? JSON.parse(data) : null;
        if (request?._tag === "Request" && request.tag === "pullRequests.update") {
          state.checkboxSave = new Promise<void>((resolve) => {
            const completed = (event: MessageEvent) => {
              const message = typeof event.data === "string" ? JSON.parse(event.data) : null;
              if (message?._tag === "Exit" && message.requestId === request.id) {
                this.removeEventListener("message", completed);
                resolve();
              }
            };
            this.addEventListener("message", completed);
          });
        }
        return send.call(this, data);
      };
    });
    await t3.open("/pull-requests");
    await screen.getByRole("button", new RegExp(`Open #${id} Verify multiline task checkboxes`)).tap();
    const edit = screen.getByRole("button", "Edit description", { exact: true });
    await edit.waitFor({ timeout: 60_000 });
    const results: string[] = [];
    const setBody = async (body: string) => {
      await edit.tap();
      await screen.getByRole("textbox", "Pull request description", { exact: true }).fill(body);
      await screen.getByRole("button", "Save", { exact: true }).tap();
      await edit.waitFor();
    };
    const clickAndRead = async (index: number, label: string) => {
      await browser.locator('[data-pr-description] input[aria-label="Toggle task"]').nth(index).click();
      await browser.evaluate(async () => {
        await (window as typeof window & { checkboxSave?: Promise<void> }).checkboxSave;
        return true;
      });
      // Reading Azure verifies the persisted upstream description after the real save finishes.
      const saved = await az(["repos", "pr", "show", "--id", String(id)]);
      results.push(saved.description);
      await app.screenshot(label);
    };
    await app.screenshot("plain-before-click");
    await clickAndRead(0, "plain-after-click");
    await setBody("> -\n>   [ ] Task");
    await app.screenshot("blockquote-before-click");
    await clickAndRead(0, "blockquote-after-click");
    await setBody("- [ ] Control\n\n-\n  [ ] Task");
    await clickAndRead(0, "control-after-click");
    await clickAndRead(1, "mixed-task-after-click");
    await expect(results).toEqual([
      "-\n  [x] Task",
      "> -\n>   [x] Task",
      "- [x] Control\n\n-\n  [ ] Task",
      "- [x] Control\n\n-\n  [x] Task",
    ]);
  } finally {
    if (id !== undefined) await az(["repos", "pr", "update", "--id", String(id), "--status", "abandoned"]);
    for (const branch of [`${tag}-head`, `${tag}-base`]) {
      const refs = await az(["repos", "ref", "list", "--project", project, "--repository", repository, "--filter", `heads/${branch}`]);
      if (refs[0]) await az(["repos", "ref", "delete", "--project", project, "--repository", repository, "--name", `refs/heads/${branch}`, "--object-id", refs[0].objectId]);
    }
  }
});
