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("flaky", { version: 1, payload: Schema.Struct({}) },
  Effect.fn(function* () {
    yield* T3.step("always-fails", { returns: Schema.Void, retry: { times: 20, schedule: Schedule.spaced("100 millis") } }, Effect.fail("boom"));
  }));
`;

test(
  "Workflow retry labels use the English ordinal for attempt 21",
  WEB,
  async ({ t3, app, screen }) => {
    const definition = await runPromise(
      Effect.map(Path.Path, (path) => path.join(T3_HOME, "workflows/flaky.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", "flaky", "--input", "{}", "--key", "one", "--json"]),
      );
      const { run } = JSON.parse(started.stdout);
      await t3.open(`/workflows?run=${run.runId}`);

      await screen.getByText("Paused at always-fails", { exact: true }).waitFor({ timeout: 30_000 });
      await app.screenshot("workflow-attempt-21");
      await expect(screen.getByText("21st try", { exact: false }).first()).toBeVisible();
    } finally {
      await workflowsOn(false);
      await runPromise(
        Effect.flatMap(FileSystem.FileSystem, (fs) => fs.remove(definition, { force: true })),
      );
    }
  },
);
