import { expect } from "e2e";
import { readFile } from "node:fs/promises";
import { setTimeout } from "node:timers/promises";
import { test, WEB } from "./t3.ts";

test("GitLab resolves a pasted repository web URL", WEB, async ({ t3, app, screen, browser }) => {
  const capture = async (label: string) => {
    let previous = await app.screenshot(`${label}-settling`);
    for (let attempt = 0; attempt < 10; attempt++) {
      await setTimeout(500);
      const current = await app.screenshot(`${label}-stable-${attempt}`);
      if ((await readFile(previous)).equals(await readFile(current))) return;
      previous = current;
    }
    throw new Error("Capture did not settle");
  };
  await t3.project("demo");
  await t3.open();
  await screen.getByRole("button", "Add project").waitFor({ state: "visible" });
  await app.open("/settings/source-control");
  const offer = screen.getByRole("switch", "Offer GitLab when adding or publishing a project");
  await offer.tap();
  await app.open("/");
  await screen.getByRole("button", "Add project").tap();
  await screen.getByRole("option", { name: "GitLab repository Clone GitLab group/project", disabled: false }).tap();
  await screen.getByPlaceholder("Enter GitLab repository (group/project)").waitFor({ state: "visible" });
  await screen.getByRole("combobox").fill("gitlab-org/cli");
  await browser.keyboard.press("Enter");
  await screen.getByText("gitlab-org/cli", { exact: true }).waitFor({ state: "visible" });
  await capture("path-control");
  await browser.keyboard.press("Escape");
  await screen.getByRole("button", "Add project").tap();
  await screen.getByRole("option", { name: "GitLab repository Clone GitLab group/project", disabled: false }).tap();
  await screen.getByPlaceholder("Enter GitLab repository (group/project)").waitFor({ state: "visible" });
  await screen.getByRole("combobox").fill("https://gitlab.com/gitlab-org/cli");
  await browser.keyboard.press("Enter");
  await screen.getByText(/^(Repository lookup failed|Select where to clone)$/).waitFor({ state: "visible" });
  await capture("pasted-url-result");
  await expect(screen.getByText("gitlab-org/cli", { exact: true })).toBeVisible();
});
