/// <reference lib="dom" />
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("An answer keeps its run after switching to All runs", WEB, async ({ t3, app, browser, 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-proof.ts`, `
export default T3.workflow("release-proof", { version: 1, payload: Schema.Struct({ title: Schema.String }) },
  Effect.fn(function* ({ title }) {
    yield* T3.title(title);
    yield* T3.ask("ship", { title: "Ship " + title + "?", choices: ["Ship", "Hold"] });
    return "Shipped";
  }));`);
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: { workflowsEnabled: true } });
    for (const [key, title] of [["spring", "Spring release"], ["summer", "Summer release"]]) {
      yield* makeState(T3_HOME).cli(["workflow", "start", "release-proof", "--key", key, "--input", JSON.stringify({ title })]);
    }
  }).pipe(Effect.scoped));
  // Delay the real answer request to reproduce the reported slow connection.
  await browser.addInitScript(() => {
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function (data) {
      if (typeof data === "string" && data.includes('"workflows.answer"')) {
        setTimeout(() => send.call(this, data), 4000);
        return;
      }
      return send.call(this, data);
    };
  });
  await t3.open("/workflows");
  await screen.getByRole("button", "Needs you", { exact: true }).tap();
  await screen.getByRole("region", "Questions waiting on you").getByRole("option", /Spring release/).tap();
  await screen.getByRole("heading", "Spring release", { exact: true }).waitFor();
  await browser.keyboard.press("1");
  await browser.keyboard.press("Enter");
  await screen.getByText("Sending Ship…", { exact: true }).waitFor();
  await screen.getByRole("button", "All runs", { exact: true }).tap();
  await app.screenshot("switched-to-all-while-sending");
  await screen.getByText(/1 waiting on you · 1 answered/).waitFor();
  await screen.getByRole("region", "Workflow runs").getByRole("option", /Spring release.*Done/s).waitFor();
  await app.screenshot("selected-run-after-answer");
  await expect(screen.getByRole("heading", "Spring release", { exact: true })).toBeVisible();
});
