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 Workflows environments fall back without crashing", 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 results: string[] = [];
  for (const [label, search] of [
    ["baseline", ""],
    ["blank-env", "?env=%20"],
    ["numeric-env", "?env=123"],
    ["numeric-selections", "?env=123&run=456&file=789"],
    ["blank-at-limit", `?env=${"%20".repeat(200)}x`],
    ["unknown-valid-env", "?env=abc"],
  ]) {
    await t3.open(`/workflows${search}`);
    await screen.getByText(/No workflow runs yet|Schema validation failed|abc is not connected/).first().waitFor({ timeout: 30_000 });
    await app.screenshot(label);
    const text = await browser.evaluate(() => document.body.innerText);
    results.push(label === "unknown-valid-env"
      ? (text.includes("abc is not connected") ? "ok" : "unexpected")
      : (text.includes("No workflow runs yet") && !text.includes("Schema validation failed") ? "ok" : "crashed"));
  }
  await expect(results).toEqual(["ok", "ok", "ok", "ok", "ok", "ok"]);
});
