/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { environmentId, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("SSH host checks explain Node and npm prerequisites", WEB, async ({ t3, app, browser, screen }) => {
  await t3.project("demo");
  const origin = app.baseUrl ?? "";
  const environment = await runPromise(environmentId(origin));
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, origin);
    yield* client["server.updateSettings"]({ patch: { enableDeviceSupport: true } });
  }).pipe(Effect.scoped));
  await t3.open(`/settings/devices?machine=${encodeURIComponent(environment)}#device-sources`);
  const outcomes: string[] = [];
  for (const [label, port] of [["Node 20", "23320"], ["Missing npm", "23322"], ["Missing Node", "23300"]]) {
    await screen.getByRole("button", "Add source", { exact: true }).tap();
    await screen.getByRole("menuitem", "Machine over SSH", { exact: true }).tap();
    await screen.getByRole("textbox", "Name", { exact: true }).fill(label);
    await screen.getByRole("textbox", "SSH target", { exact: true }).fill("root@127.0.0.1");
    await screen.getByText("SSH options", { exact: true }).tap();
    await screen.getByRole("spinbutton", "Port", { exact: true }).fill(port);
    await screen.getByRole("button", "Test connection", { exact: true }).tap();
    await screen.getByText("Show error", { exact: true }).waitFor();
    await screen.getByText("Show error", { exact: true }).tap();
    await app.screenshot(label.toLowerCase().replaceAll(" ", "-"));
    outcomes.push(await browser.evaluate(() => document.body.innerText));
    await screen.getByRole("button", "Cancel", { exact: true }).tap();
  }
  expect(outcomes[0]).toContain("Connected over SSH, but this host's Node is older than 22.12. Install Node 22.12 or newer.");
  expect(outcomes[1]).toContain("Connected over SSH, but npm is not on this host's PATH for non-interactive SSH commands.");
  expect(outcomes[2]).toContain("Connected over SSH, but Node is not on this host's PATH for non-interactive SSH commands.");
  expect(outcomes.join("\n")).not.toContain("PRIVATE_PROBE_BANNER");
});
