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

test("Workflow subjects keep their issue, URL, and pull request glyphs", WEB, async ({ t3, app, browser, screen }) => {
  await t3.project("demo");
  const cases = [
    { title: "Plain page", subject: "https://example.com/report?next=/pull/8#/issues/9" },
    { title: "Typed issue", subject: { projectId: "proj-demo", tracker: "github", host: "github.com", scope: "acme/app", key: "7", url: "https://github.com/acme/app/issues/7?next=/pull/8" } },
    { title: "Real PR", subject: "https://github.com/acme/app/pull/8" },
    { title: "Control issue (no query)", subject: { projectId: "proj-demo", tracker: "github", host: "github.com", scope: "acme/app", key: "6", url: "https://github.com/acme/app/issues/6" } },
  ];
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.makeDirectory(`${T3_HOME}/workflows`, { recursive: true });
    yield* fs.writeFileString(`${T3_HOME}/workflows/glyphs.ts`, `export default T3.workflow("glyphs", { version: 1, payload: Schema.Struct({ title: Schema.String, subject: Schema.Unknown }) }, Effect.fn(function* (input) { yield* T3.title(input.title); yield* T3.subject(input.subject); yield* T3.ask("review", { title: "Review subject", choices: ["Done"] }); }));`);
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: { workflowsEnabled: true } });
    for (const [index, input] of cases.entries()) {
      yield* makeState(T3_HOME).cli(["workflow", "start", "glyphs", "--key", String(index), "--input", JSON.stringify(input)]);
    }
  }).pipe(Effect.scoped));
  await t3.open("/workflows");
  const observations: boolean[] = [];
  for (const scope of ["All runs", "Needs you"]) {
    await screen.getByRole("button", scope, { exact: true }).tap();
    for (const item of cases) await browser.locator('[role="option"]').filter({ hasText: item.title }).waitFor();
    await app.screenshot(scope === "All runs" ? "all-runs-subject-glyphs" : "needs-you-subject-glyphs");
    for (const [title, glyph] of [["Plain page", "workflow"], ["Typed issue", "circle-dot"], ["Real PR", "git-pull-request-arrow"], ["Control issue (no query)", "circle-dot"]]) {
      observations.push(await browser.locator(`[role="option"]:has-text("${title}") svg.lucide-${glyph}`).isVisible());
    }
  }
  expect(observations).toEqual(Array(8).fill(true));
});
