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

test("Root directory imports precede importers and above-root imports create no dependency", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("Review ordering", {
    "index.ts": "export const x = 1;\n", "app.ts": "export const app = 1;\n",
    "a.ts": "export const a = 1;\n", "z.ts": "export const z = 1;\n",
  });
  await runPromise(run("git", ["remote", "add", "origin", "https://gitlab.com/julius54/diff-order-proof-44987.git"], {cwd: project}));
  const thread = await t3.thread({project, title: "Review file ordering", messages: ["first"]});
  await browser.setViewport({width: 1440, height: 1000});
  await t3.open(thread);
  const orders: string[][] = [];
  for (const [number, label] of [[1, "root-index"], [2, "above-root"]] as const) {
    await t3.open(`/pull-requests?${new URLSearchParams({q: label})}`);
    await screen.getByRole("button", new RegExp(label)).first().tap();
    await screen.getByRole("button", "Code", {exact:true}).tap();
    await screen.getByRole("button", "Expand all files", {exact:true}).tap();
    await expect.poll(async () => browser.evaluate(() => {
      function titles(root: Document | ShadowRoot): string[] {
        const result: string[] = [];
        for (const element of root.querySelectorAll("*")) {
          if (element.hasAttribute("data-title")) result.push(element.textContent?.trim() ?? "");
          if (element.shadowRoot) result.push(...titles(element.shadowRoot));
        }
        return result;
      }
      return titles(document).filter(t => /^(index|app|a|z)\.ts$/.test(t));
    }), {timeout:60000}).toHaveLength(2);
    orders.push(await browser.evaluate(() => {
      function titles(root: Document | ShadowRoot): string[] {
        const result: string[] = [];
        for (const element of root.querySelectorAll("*")) {
          if (element.hasAttribute("data-title")) result.push(element.textContent?.trim() ?? "");
          if (element.shadowRoot) result.push(...titles(element.shadowRoot));
        }
        return result;
      }
      return titles(document).filter(t => /^(index|app|a|z)\.ts$/.test(t));
    }));
    await app.screenshot(label);
  }
  expect(orders).toEqual([["index.ts", "app.ts"], ["a.ts", "z.ts"]]);
});
