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

const endpoint = "projects/89769593/merge_requests/1/notes/4375933718/award_emoji";
const api = async (...args: string[]) => JSON.parse((await runPromise(run("glab", ["api", ...args]))).stdout || "null");

test("A reaction removed on GitLab stays removed after refresh", WEB, async ({t3, app, browser, screen}) => {
  for (const award of await api(endpoint)) await api("-X", "DELETE", `${endpoint}/${award.id}`);
  const project = await t3.project("reaction-example");
  await runPromise(run("git", ["remote", "add", "origin", "https://gitlab.com/julius54/reaction-refresh-proof-47470.git"], {cwd: project}));
  await browser.setViewport({width: 1440, height: 1000});
  await browser.addInitScript(() => {
    const activityIds = new Set<string>();
    const watched = new WeakSet<WebSocket>();
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if (typeof data === "string") for (const req of [JSON.parse(data)].flat()) {
        if (req.tag === "pullRequests.activity") activityIds.add(String(req.id));
      }
      if (!watched.has(this)) {
        watched.add(this);
        this.addEventListener("message", event => {
          if (typeof event.data !== "string") return;
          for (const response of [JSON.parse(event.data)].flat()) {
            if (response._tag === "Exit" && response.exit?._tag === "Success" && activityIds.has(String(response.requestId))) {
              document.documentElement.dataset.activityReceived = "yes";
              if (JSON.stringify(response).includes('"viewerHasReacted":true')) document.documentElement.dataset.hostThumb = "yes";
            }
          }
        });
      }
      return send.call(this, data);
    };
  });
  await t3.open("/pull-requests");
  await screen.getByRole("button", /Open #1 Reaction refresh example/).click();
  await screen.getByRole("button", "Timeline", {exact: true}).click();
  await screen.getByRole("button", /^1 comment 1 author/).click();
  const comment = browser.locator('article').filter({hasText: "Please verify the reaction stays removed after refreshing."}).last();
  await comment.waitFor({timeout: 60000});
  await comment.getByRole("button", {name: "Add a reaction", exact: true}).click();
  await screen.getByRole("button", "thumbs up", {exact: true}).click();
  // Read the real host until the app's mutation has been saved before refreshing.
  let awards: Array<{id: number; name: string}> = [];
  for (let attempt=0; attempt<20; attempt++) {
    awards = await api(endpoint);
    if (awards.some(x=>x.name === "thumbsup")) break;
  }
  if (!awards.some(x=>x.name === "thumbsup")) throw new Error("GitLab did not save the thumbs-up");
  await screen.getByRole("button", "Refresh pull requests", {exact: true}).click();
  await comment.getByRole("button", {name: "thumbs up, 1", exact: true}).waitFor();
  await browser.locator('html[data-host-thumb="yes"]').waitFor();
  for (const award of awards) await api("-X", "DELETE", `${endpoint}/${award.id}`);
  if ((await api(endpoint)).length !== 0) throw new Error("GitLab reaction was not removed");
  await browser.evaluate(() => { delete document.documentElement.dataset.activityReceived; });
  await screen.getByRole("button", "Refresh pull requests", {exact: true}).click();
  await browser.locator('html[data-activity-received="yes"]').waitFor();
  await browser.locator('button[aria-label="Refresh pull requests"]:not(:disabled)').waitFor();
  await screen.getByRole("button", "More merge request actions", {exact: true}).waitFor();
  try {
    await expect(comment.getByRole("button", {name: "thumbs up, 1", exact: true})).toHaveCount(0);
  } finally {
    await app.screenshot("after-host-removal-and-refresh");
  }
});
