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

test("Scheduled task branch search shows loading until its real first page arrives", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("demo");
  for (const name of [...Array.from({length:110}, (_,i) => `feature-${String(i).padStart(3,"0")}`), "feature-omega"]) {
    await runPromise(run("git", ["branch", name], {cwd:project}));
  }
  await t3.thread({project, title:"Demo", messages:["Start"]});
  await browser.addInitScript(() => {
    const requests = new WeakMap<WebSocket, Set<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 === "vcs.listRefs" && request.payload?.query === "feature-omega") {
          let ids = requests.get(this); if (!ids) requests.set(this, ids = new Set());
          ids.add(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 wire = typeof data === "string" ? [JSON.parse(data)].flat() : [];
        if(wire.some(m => m?._tag === "Exit" && requests.get(this)?.has(String(m.requestId)))) {
          document.documentElement.dataset.searchHeld = "true";
          document.addEventListener("release-search", () => listener.call(this,event), {once:true});
        } else listener.call(this,event);
      },options);
    } as typeof WebSocket.prototype.addEventListener;
  });
  await t3.open("/settings/scheduled-tasks");
  await screen.getByRole("button", "New task").tap();
  await screen.getByRole("combobox", "Project", {exact:true}).tap();
  await screen.getByRole("option", "demo", {exact:true}).tap();
  await browser.locator("#scheduled-task-base-ref").click();
  await screen.getByText("Showing 100 of 112 refs", {exact:true}).waitFor();
  await app.screenshot("initial-branches");
  await screen.getByPlaceholder("Search refs...").fill("feature-omega");
  await browser.locator('html[data-search-held="true"]').waitFor();
  // Keep the real response held for the reported observation interval in the recording.
  await browser.evaluate(() => new Promise<void>(resolve => setTimeout(resolve, 5500)));
  await app.screenshot("search-pending");
  const loading = await screen.getByText("Loading refs...", {exact:true}).isVisible();
  const empty = await screen.getByText("No refs found.", {exact:true}).isVisible();
  await browser.evaluate(() => {document.dispatchEvent(new Event("release-search")); return null;});
  await screen.getByRole("option", /^feature-omega/).waitFor();
  await app.screenshot("search-completed");
  await screen.getByPlaceholder("Search refs...").fill("feature-missing");
  await screen.getByText("No refs found.", {exact:true}).waitFor();
  await app.screenshot("missing-completed");
  expect(loading, "Pending search must show Loading refs...").toBe(true);
  expect(empty, "Pending search must not claim no refs exist").toBe(false);
});
