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

const definitions = {
  "links.ts": `export default T3.workflow("links", { version: 1, payload: Schema.Struct({}) }, Effect.fn(function* () {
    yield* T3.ask("review", { title: "Build this?", choices: ["Yes", "No"], links: [{ label: "The request", url: "https://example.com/1" }] });
  }));`,
  "subject.ts": `export default T3.workflow("subject", { version: 1, payload: Schema.Struct({}) }, Effect.fn(function* () {
    yield* T3.subject("https://status.example.com/incidents/9");
    yield* T3.ask("review", { title: "Review this incident?", choices: ["Yes", "No"] });
  }));`,
};

test("Workflow links and untitled URL subjects render without URL static methods", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("workflow-proof");
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    const path = yield* Path.Path;
    const directory = path.join(T3_HOME, "workflows");
    yield* fs.makeDirectory(directory, { recursive: true });
    for (const [name, source] of Object.entries(definitions)) yield* fs.writeFileString(path.join(directory, name), source);
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: { workflowsEnabled: true } });
  }).pipe(Effect.scoped));
  const cli = (args: string[]) => runPromise(makeState(T3_HOME).cli(args));
  const links = JSON.parse((await cli(["workflow", "start", "links", "--key", "one", "--json"])).stdout).run;
  const subject = JSON.parse((await cli(["workflow", "start", "subject", "--key", "one", "--json"])).stdout).run;
  await browser.addInitScript(() => {
    const method = sessionStorage.getItem("missing-url-method") ?? "parse";
    Object.defineProperty(URL, method, { value: undefined, configurable: true });
  });
  const failures: unknown[] = [];
  await t3.open(`/workflows?run=${links.runId}`);
  try {
    await expect(screen.getByRole("link", "The request", { exact: true })).toBeVisible();
    await expect(screen.getByRole("button", "Yes", { exact: true })).toBeVisible();
    await expect(screen.getByRole("button", "No", { exact: true })).toBeVisible();
  } catch (error) { failures.push(error); }
  await app.screenshot("question-without-url-parse");
  await browser.evaluate(() => sessionStorage.setItem("missing-url-method", "canParse"));
  await t3.open(`/workflows?run=${subject.runId}`);
  try {
    await expect(screen.getByText("status.example.com", { exact: true }).first()).toBeVisible();
    await expect(screen.getByText("Review this incident?", { exact: true }).first()).toBeVisible();
  } catch (error) { failures.push(error); }
  await app.screenshot("subject-without-url-canparse");
  if (failures.length) throw failures[0];
});
