import { expect } from "e2e";
import * as fs from "node:fs/promises";
import * as os from "node:os";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Uppercase local IPv6 SSH sources use the local device summary", WEB, async ({ t3, app, screen }) => {
  const address = os.networkInterfaces().tailscale0?.find((entry) => entry.family === "IPv6" && !entry.address.startsWith("fe80"))?.address;
  if (!address) throw new Error("A real Tailscale IPv6 interface is required");
  const config = `${os.homedir()}/.ssh/config`;
  const original = await fs.readFile(config, "utf8").catch(() => null);
  const aliases = [["upper", address.toUpperCase()], ["lower", address], ["expanded", "0:0:0:0:0:0:0:1"], ["remote", "2001:DB8::1"]];
  await fs.mkdir(`${os.homedir()}/.ssh`, { recursive: true });
  await fs.writeFile(config, aliases.map(([name, host]) => `Host t3-proof-ipv6-${name}\n HostName ${host}\n Port 22\n ProxyCommand none\n ProxyJump none\n ConnectTimeout 3\n`).join("\n") + "\n" + (original ?? ""), { mode: 0o600 });
  try {
    await t3.project("IPv6 device proof");
    await t3.open("/settings/devices");
    const observed: Record<string, {local: boolean; retained: boolean; persisted: boolean}> = {};
    for (const name of ["lower", "expanded", "remote", "upper"]) {
      await screen.getByRole("button", "Add source").tap();
      await screen.getByRole("menuitem", "Machine over SSH").tap();
      await screen.getByRole("textbox", "Name", { exact: true }).fill(`${name} IPv6 source`);
      await screen.getByRole("textbox", "SSH target", { exact: true }).fill(`t3-proof-ipv6-${name}`);
      await screen.getByRole("button", "Test connection", { exact: true }).tap();
      await screen.getByRole("status").filter({ hasText: /checks passed|failed/i }).waitFor();
      const local = await screen.getByText("Already available locally", { exact: true }).isVisible();
      if (!local) await screen.getByText("Show error", { exact: true }).tap();
      await app.screenshot(`${name}-ipv6-connection-check`);
      await screen.getByRole("button", "Save host", { exact: true }).tap();
      await screen.getByRole("dialog", "Add device host", { exact: true }).waitFor({ state: "hidden" });
      await app.screenshot(`${name}-ipv6-saved-sources`);
      const retained = await screen.getByText(`t3-proof-ipv6-${name}`, { exact: true }).isVisible();
      const settings = JSON.parse(await fs.readFile(`${T3_HOME}/userdata/settings.json`, "utf8"));
      const persisted = (settings.deviceHosts ?? []).some((host: {target?: string}) => host.target === `t3-proof-ipv6-${name}`);
      observed[name] = {local, retained, persisted};
    }
    expect(observed).toEqual({
      lower: {local: true, retained: false, persisted: false},
      expanded: {local: true, retained: false, persisted: false},
      remote: {local: false, retained: true, persisted: true},
      upper: {local: true, retained: false, persisted: false},
    });
  } finally {
    if (original === null) await fs.unlink(config); else await fs.writeFile(config, original);
  }
});
