import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Malformed workflow links select the last tab and discard unreadable panes", WEB, async ({ t3, app, browser, screen }) => {
  await t3.project("demo");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: { workflowsEnabled: true } });
  }).pipe(Effect.scoped));
  const pane = encodeURIComponent(JSON.stringify([{ kind: "issue", key: "i412" }, { kind: "pullRequest", key: "p418" }]));
  const results: Array<{ input: string; selected: string | null; tab: string | null }> = [];
  for (const input of ["absent", "", "null", "false", "%20", "true", "-1"]) {
    await t3.open(`/workflows?pane=${pane}${input === "absent" ? "" : `&tab=${input}`}`);
    await screen.getByRole("tab", "pullRequest", { exact: true }).waitFor();
    await app.screenshot(`tab-${input === "" ? "empty" : input === "%20" ? "whitespace" : input}`);
    results.push(await browser.evaluate((input) => ({ input, selected: document.querySelector('[role="tab"][aria-selected="true"]')?.textContent ?? null, tab: new URL(location.href).searchParams.get("tab") }), input));
  }
  await t3.open("/workflows?pane=nope&tab=0");
  await browser.locator("h1").waitFor();
  await app.screenshot("unreadable-pane");
  const unreadable = await browser.evaluate(() => ({ heading: document.querySelector("h1")?.textContent ?? null, pane: new URL(location.href).searchParams.get("pane"), tab: new URL(location.href).searchParams.get("tab") }));
  await expect(results).toEqual(["absent", "", "null", "false", "%20", "true", "-1"].map(input => ({ input, selected: "pullRequest", tab: null })));
  await expect(unreadable).toEqual({ heading: "Workflows", pane: null, tab: null });
});
