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

test("A GitLab publish summary keeps the actual provider after a pending selection change", WEB, async ({t3, app, browser, screen}) => {
  const name = `t3-proof-47383-${crypto.randomUUID().slice(0, 8)}`;
  const project = await t3.project("demo-repo", {"README.md": "# Publish wizard proof\n"});
  const thread = await t3.thread({project, title: "Publish repository proof", messages: ["Start"]});
  await browser.addInitScript(() => {
    const ids = new WeakMap<WebSocket, string>();
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if (typeof data === "string") for (const request of [JSON.parse(data)].flat()) {
        if (request?._tag === "Request" && request.tag === "sourceControl.publishRepository") ids.set(this, String(request.id));
      }
      return send.call(this, data);
    };
    const listen = WebSocket.prototype.addEventListener;
    WebSocket.prototype.addEventListener = function(this: WebSocket, type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions) {
      if (type !== "message" || typeof listener !== "function") return listen.call(this, type, listener, options);
      return listen.call(this, type, (event: Event) => {
        const data = (event as MessageEvent).data;
        const messages = typeof data === "string" ? [JSON.parse(data)].flat() : [];
        if (messages.some(m => m?._tag === "Exit" && String(m.requestId) === ids.get(this))) {
          document.documentElement.dataset.publishReply = "held";
          document.addEventListener("release-publish", () => listener.call(this, event), {once:true});
        } else listener.call(this, event);
      }, options);
    } as typeof WebSocket.prototype.addEventListener;
  });
  try {
    await t3.open("/settings/source-control");
    const offer = screen.getByRole("switch", "Offer GitLab when adding or publishing a project");
    await offer.tap();
    await t3.open(thread);
    await screen.getByRole("button", "Publish repository", {exact:true}).tap();
    await screen.getByRole("radio", "GitLab", {exact:true}).tap();
    await screen.getByRole("button", "Next", {exact:true}).tap();
    await screen.getByRole("textbox", "Repository", {exact:true}).fill(`julius54/${name}`);
    await screen.getByRole("button", "Advanced", {exact:true}).tap();
    await screen.getByRole("button", "HTTPS", {exact:true}).tap();
    await screen.getByRole("button", "Publish", {exact:true}).tap();
    await browser.locator("html[data-publish-reply=held]").waitFor({timeout: 60_000});
    // Native click honors disabled, allowing the identical attempt on both commits.
    await browser.evaluate(() => {
      (document.querySelector('button[aria-label="Provider, step 1, GitLab"]') as HTMLButtonElement).click();
      return null;
    });
    const github = screen.getByRole("radio", "GitHub", {exact:true});
    if (await github.isVisible()) await github.tap();
    await browser.evaluate(async () => { await new Promise(resolve => setTimeout(resolve, 750)); return null; });
    await app.screenshot("pending-publish-provider-change-attempt");
    await browser.evaluate(() => { document.dispatchEvent(new Event("release-publish")); return null; });
    await screen.getByText("Repository published", {exact:true}).waitFor();
    await browser.evaluate(async () => { await new Promise(resolve => setTimeout(resolve, 750)); return null; });
    await app.screenshot("completed-gitlab-publish");
    await expect(screen.getByText("main is now live on GitLab.", {exact:true})).toBeVisible();
    await expect(screen.getByRole("button", "Open on GitLab", {exact:true})).toBeVisible();
    await expect(screen.getByRole("button", "Provider, step 1, GitLab", {exact:true})).toBeVisible();
  } finally {
    await runPromise(run("glab", ["api", "--method", "DELETE", `projects/julius54%2F${name}`], {allowExit:[0,1]}));
  }
});
