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 { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Grouped SSH check stays pending after a linked environment disconnects", WEB, async ({ t3, app, browser, screen }) => {
  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");
  const origin = app.baseUrl ?? "";
  const server = startSecondServer(origin);
  const saveHost = (home: string, url: string, id: string) => runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(home, url);
    yield* client[WS_METHODS.serverUpdateSettings]({ patch: {
      enableDeviceSupport: true,
      deviceHosts: [{ kind: "ssh", id, label: "Slow SSH host", target: "127.0.0.1", port: address.port }],
    } });
  }).pipe(Effect.scoped));
  try {
    await t3.project("demo");
    await saveHost(T3_HOME, origin, "slow-host");
    const { host, token } = await server.ready;
    await saveHost(SECOND_HOME, host, "linked-slow-host");
    await t3.open("/settings/connections");
    await screen.getByRole("button", "Add environment").tap();
    const dialog = screen.getByRole("dialog");
    await dialog.getByPlaceholder("backend.example.com").fill(host);
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button", "Add environment").tap();
    await screen.getByRole("button", "More actions for Scenario").waitFor();
    await app.open("/settings/devices#device-sources");
    await screen.getByText("Simulators and emulators installed on each environment's own machine.").waitFor();
    const more = browser.locator("#device-sources").getByRole("button", "More", { exact: true });
    const pending = screen.getByText("Testing connection", { exact: true });
    await more.tap();
    await screen.getByRole("menuitem", "Test connection", { exact: true }).tap();
    await pending.waitFor();
    await app.screenshot("grouped-check-pending");
    await server.stop();
    await screen.getByText("Simulators and emulators installed on this environment's machine.").waitFor();
    await app.screenshot("after-linked-disconnect");
    expect(await pending.isVisible(), "The surviving SSH row keeps its pending check after disconnect").toBe(true);
    for (const socket of sockets) socket.destroy();
    await expect(pending).not.toBeVisible();
    await app.screenshot("surviving-check-finished");
  } finally {
    await server.stop();
    for (const socket of sockets) socket.destroy();
    await new Promise<void>(resolve => slowHost.close(() => resolve()));
  }
});
