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 DEFINITION = `export default T3.workflow("review-links", { version: 1, payload: Schema.Struct({}) },
  Effect.fn(function* () {
    yield* T3.step("Check draft", { returns: Schema.String },
      Effect.fail("See [Review [draft]](https://example.com/a_(b))."));
  }));
`;

test("Workflow timeline keeps nested link labels", WEB, async ({ t3, app, screen, browser }) => {
  await browser.setViewport({ width: 1100, height: 800 });
  const definition = await runPromise(
    Effect.gen(function* () {
      return (yield* Path.Path).join(T3_HOME, "workflows", "review-links.ts");
    }),
  );
  const workflowsOn = (on: boolean) =>
    runPromise(
      Effect.gen(function* () {
        const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
        yield* client["server.updateSettings"]({ patch: { workflowsEnabled: on } });
      }).pipe(Effect.scoped),
    );

  try {
    await runPromise(
      Effect.gen(function* () {
        const fs = yield* FileSystem.FileSystem;
        const path = yield* Path.Path;
        yield* fs.makeDirectory(path.dirname(definition), { recursive: true });
        yield* fs.writeFileString(definition, DEFINITION);
      }),
    );
    await t3.project("demo");
    await workflowsOn(true);
    const started = await runPromise(
      makeState(T3_HOME).cli(["workflow", "start", "review-links", "--key", "one", "--json"]),
    );
    const { run } = JSON.parse(started.stdout);
    await t3.open(`/workflows?run=${run.runId}`);

    const step = screen.getByRole("button", /^Check draft See/);
    const summary = step.getByText(/^See /);
    await summary.waitFor({ timeout: 30_000 });
    await app.screenshot("workflow-timeline-summary");
    await expect(summary).toHaveText("See Review [draft].");
  } finally {
    await workflowsOn(false);
    await runPromise(
      Effect.gen(function* () {
        yield* (yield* FileSystem.FileSystem).remove(definition, { force: true });
      }),
    );
  }
});
