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";

const definition = (name: string, value: string) =>
  `T3.workflow(${JSON.stringify(name)}, { version: 1, payload: Schema.Struct({}) }, Effect.fn(function* () { yield* T3.title(${JSON.stringify(value)}); return ${JSON.stringify(value)}; }))`;
const duplicate = `export default [${definition("review", "copy-a")}, ${definition("review", "copy-b")}];`;

test(
  "An externally duplicated version retains the last good file and does not displace another file at startup",
  WEB,
  async ({ t3, app, screen, browser }) => {
    await browser.addInitScript(() => {
      document.addEventListener("DOMContentLoaded", () => {
        const style = document.createElement("style");
        style.textContent = `p code { font-size: 0 !important; } p code::after { content: "[workflow folder]"; font-size: 12px; }`;
        document.head.append(style);
      });
    });
    await t3.project("workflow-demo");
    const settings = (enabled: boolean) =>
      runPromise(
        Effect.gen(function* () {
          const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
          return yield* client["server.updateSettings"]({ patch: { workflowsEnabled: enabled } });
        }).pipe(Effect.scoped),
      );
    const read = () =>
      runPromise(
        Effect.gen(function* () {
          const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
          return yield* client["workflows.getDefinition"]({});
        }).pipe(Effect.scoped),
      );
    const write = (name: string, source: string) =>
      runPromise(
        Effect.gen(function* () {
          const fs = yield* FileSystem.FileSystem;
          yield* fs.makeDirectory(`${T3_HOME}/workflows`, { recursive: true });
          yield* fs.writeFileString(`${T3_HOME}/workflows/${name}`, source);
        }),
      );
    const cli = (args: string[], exits = [0]) =>
      runPromise(makeState(T3_HOME).cli(["workflow", ...args], exits));
    await write("review.ts", `export default ${definition("review", "v1")};`);
    await settings(true);
    await cli(["start", "review", "--key", "initial"]);
    await t3.open("/workflows?definitions=true");
    await screen.getByText("review.ts", { exact: true }).waitFor();
    const revision = (await read()).revision;
    await write("review.ts", duplicate);
    await expect.poll(async () => (await read()).revision).toBeGreaterThan(revision);
    await t3.open("/workflows?definitions=true");
    await screen.getByText("review.ts", { exact: true }).waitFor();
    const reload = await read();
    const reloadId = JSON.parse(
      (await cli(["start", "review", "--key", "reload", "--json"])).stdout,
    ).run.runId;
    await app.screenshot("reload-duplicate-definitions");
    await t3.open("/workflows");
    await screen
      .getByRole("heading", /v1|copy-a/)
      .first()
      .waitFor();
    await app.screenshot("reload-run-result");
    const reloadRun = JSON.parse((await cli(["show", reloadId, "--json"])).stdout).run;
    await settings(false);
    await write(
      "zeta.ts",
      `export default [${definition("review", "zeta")}, ${definition("other", "other-ok")}];`,
    );
    await settings(true);
    const bootId = JSON.parse((await cli(["start", "review", "--key", "boot", "--json"])).stdout)
      .run.runId;
    const other = await cli(["start", "other", "--key", "boot-other", "--json"], [0, 1, 2]);
    await t3.open("/workflows?definitions=true");
    await screen.getByText("zeta.ts", { exact: true }).waitFor();
    await app.screenshot("startup-duplicate-definitions");
    const startup = await read();
    await t3.open("/workflows");
    await screen
      .getByRole("heading", /v1|copy-a|zeta|other-ok/)
      .first()
      .waitFor();
    await app.screenshot("startup-run-results");
    const bootRun = JSON.parse((await cli(["show", bootId, "--json"])).stdout).run;
    const otherRun =
      other.exitCode === 0
        ? JSON.parse((await cli(["show", JSON.parse(other.stdout).run.runId, "--json"])).stdout).run
        : undefined;
    expect({
      reloadProblem:
        reload.files.find((f) => f.name === "review.ts")?.problems.some(() => true) ?? false,
      reloadResult: reloadRun.result,
      startupInvalid: startup.files.find((f) => f.name === "review.ts")?.workflows,
      startupValid: startup.files.find((f) => f.name === "zeta.ts")?.workflows,
      bootResults: [bootRun.result, otherRun?.result].sort(),
      otherStarted: other.exitCode === 0,
    }).toEqual({
      reloadProblem: true,
      reloadResult: "v1",
      startupInvalid: [],
      startupValid: ["review@1", "other@1"],
      bootResults: ["other-ok", "zeta"],
      otherStarted: true,
    });
  },
);
