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("Opening a run preserves the picked build question", WEB, async ({ t3, app, screen }) => {
  await t3.project("release-demo");
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.makeDirectory(`${T3_HOME}/workflows`, { recursive: true });
    yield* fs.writeFileString(`${T3_HOME}/workflows/release.ts`, `
const { workflow, ask, wait, title } = T3;
export default workflow("release", { version: 1, payload: Schema.Struct({ name: Schema.String }) },
  Effect.fn(function* (payload) {
    yield* title("Release " + payload.name);
    yield* Effect.all([
      ask("notes", { title: "Approve release notes for v2.4?", choices: ["Approve notes", "Rewrite notes"] }),
      Effect.gen(function* () {
        yield* wait("build-ready", { returns: Schema.Null });
        yield* ask("build", { title: "Approve build for v2.4?", choices: ["Ship build", "Hold build"] });
      })
    ], { concurrency: "unbounded" });
  }));`);
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: { workflowsEnabled: true } });
    const cli = makeState(T3_HOME).cli;
    const started = yield* cli(["workflow", "start", "release", "--key", "release-proof", "--input", '{"name":"v2.4"}']);
    console.log("STARTED", started.stdout);
    const runs = yield* cli(["workflow", "list", "--json"]);
    const data = JSON.parse(runs.stdout);
    const run = Array.isArray(data) ? data[0] : (data.runs ?? data.items)[0];
    yield* cli(["workflow", "signal", "null", "--run", run.runId ?? run.id, "--wait", "build-ready"]);
  }).pipe(Effect.scoped));
  await t3.open("/workflows");
  await screen.getByRole("button", "Needs you", { exact: true }).tap();
  await screen.getByRole("option").nth(1).tap();
  await screen.getByText("Approve build for v2.4?", { exact: true }).waitFor();
  await app.screenshot("picked-build-question");
  await screen.getByRole("button", /^Open run/).tap();
  await screen.getByRole("button", /^Back to decision/).waitFor();
  await app.screenshot("opened-run");
  await screen.getByRole("button", /^Back to decision/).tap();
  await app.screenshot("back-to-decision");
  await expect(screen.getByText("Approve build for v2.4?", { exact: true })).toBeVisible();
  await expect(screen.getByRole("button", /Ship build/)).toBeVisible();
  await expect(screen.getByRole("button", /Hold build/)).toBeVisible();
});
