/// <reference lib="dom" />
import { readFileSync, readlinkSync, utimesSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const reason = "Changelog is missing the migration note for v2";
test("Unsent workflow reason survives environment reconnect", WEB, async ({ t3, app, browser, screen }) => {
  await t3.project("widget-v2");
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.makeDirectory(`${T3_HOME}/workflows`, { recursive: true });
    yield* fs.writeFileString(`${T3_HOME}/workflows/review.ts`, `export default T3.workflow("review", { version: 1, payload: Schema.Struct({}) }, Effect.fn(function* () { yield* T3.title("Review widget-v2"); yield* T3.ask("approve", { title: "Approve widget-v2?", choices: ["Approve", { value: "Reject", requireReason: true }] }); }));`);
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: { workflowsEnabled: true } });
    yield* makeState(T3_HOME).cli(["workflow", "start", "review", "--key", "widget-v2"]);
  }).pipe(Effect.scoped));
  const env = await runPromise(environmentId(app.baseUrl ?? ""));
  const observed: Record<string, string> = {};
  for (const pinned of [false, true]) {
    const label = pinned ? "pinned-environment" : "all-environments";
    await t3.open(`/workflows?${pinned ? `env=${env}&` : ""}view=queue`);
    const field = screen.getByRole("textbox", "Reason for Approve widget-v2?", { exact: true });
    await field.waitFor({ timeout: 30_000 });
    await field.fill(reason);
    await app.screenshot(`${label}-typed-unsent-reason`);

    const runtime = JSON.parse(readFileSync(`${T3_HOME}/userdata/server-runtime.json`, "utf8"));
    const port = new URL(runtime.origin).port;
    const listeners = execFileSync("ss", ["-H", "-ltnp", `sport = :${port}`], { encoding: "utf8" });
    const pid = Number(listeners.match(/pid=(\d+)/)?.[1]);
    if (!pid || !readlinkSync(`/proc/${pid}/cwd`).startsWith(APP_DIR)) throw new Error("Server owner is not this checkout");
    process.kill(pid, "SIGTERM");
    try {
      await screen.getByText(pinned ? /is not connected/ : "No environment connected", { exact: !pinned }).waitFor({ timeout: 30_000 });
      await app.screenshot(`${label}-disconnected`);
    } finally { const now = new Date(); utimesSync(`${APP_DIR}/apps/server/src/bin.ts`, now, now); }
    await field.waitFor({ timeout: 45_000 });
    await app.screenshot(`${label}-reason-after-reconnect`);
    observed[label] = await browser.evaluate(() => (document.querySelector('textarea[aria-label="Reason for Approve widget-v2?"]') as HTMLTextAreaElement).value);
  }
  expect(observed).toEqual({ "all-environments": reason, "pinned-environment": reason });
});
