import { createServer, type Socket } from "node:net";
import { WS_METHODS } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Repeated Test connection keeps the SSH check pending", WEB, async ({ t3, app, browser, screen }) => {
  // A real TCP endpoint accepts SSH connections but withholds its handshake.
  const sockets = new Set<Socket>();
  const slowHost = createServer(socket => {
    sockets.add(socket);
    socket.on("error", () => {});
    socket.on("close", () => sockets.delete(socket));
  });
  await new Promise<void>(resolve => slowHost.listen(0, "127.0.0.1", resolve));
  const address = slowHost.address();
  if (!address || typeof address === "string") throw new Error("No SSH fixture port");
  try {
    await t3.project("demo");
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      yield* client[WS_METHODS.serverUpdateSettings]({ patch: {
        enableDeviceSupport: true,
        deviceHosts: [{ kind: "ssh", id: "slow-host", label: "Slow SSH host", target: "127.0.0.1", port: address.port }],
      } });
    }).pipe(Effect.scoped));
    await t3.open("/settings/devices#device-sources");
    const more = browser.locator("#device-sources").getByRole("button", "More", { exact: true });
    const check = screen.getByRole("menuitem", "Test connection", { exact: true });
    const pending = screen.getByText("Testing connection", { exact: true });
    await more.tap();
    await check.tap();
    await pending.waitFor();
    await app.screenshot("first-check-pending");
    await more.tap();
    await check.tap();
    await app.screenshot("after-repeat-check");
    expect(await pending.isVisible(), "Testing connection stays visible while the SSH handshake is unfinished").toBe(true);
    for (const socket of sockets) socket.destroy();
    await expect(pending).not.toBeVisible();
    await app.screenshot("check-finished");
  } finally {
    for (const socket of sockets) socket.destroy();
    await new Promise<void>(resolve => slowHost.close(() => resolve()));
  }
});
