import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Authorized clients preserves the paired phone's Tailscale address", WEB, async ({ t3, app, screen, browser }) => {
  const pairing = execFileSync(process.execPath, ["apps/server/src/bin.ts", "pair", "--base-dir", T3_HOME], { cwd: APP_DIR, encoding: "utf8" });
  const credential = /Token: (\S+)/.exec(pairing)?.[1];
  const origin = /\((http:\/\/[^)]+)\)/.exec(pairing)?.[1];
  if (!credential || !origin) throw new Error("Pair command did not return connection details");
  const response = await fetch(`${origin}/api/auth/browser-session`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-Forwarded-For": "100.64.0.2",
      "X-Forwarded-Host": "host-a.tailnet-name.ts.net",
      "X-Forwarded-Proto": "https",
      "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1",
    },
    body: JSON.stringify({ credential }),
  });
  if (response.status !== 200 || !response.headers.get("set-cookie")) throw new Error(`Pairing failed: ${response.status}`);
  await t3.project("Pairing evidence");
  await t3.open();
  await screen.getByText("Pairing evidence", { exact: true }).first().waitFor({ state: "visible" });
  await app.open("/settings/access");
  await screen.getByText("Authorized clients", { exact: true }).tap();
  await screen.getByText("iOS", { exact: false }).first().waitFor({ state: "visible" });
  await browser.evaluate(async () => {
    const panel = document.querySelector('#authorized-clients [data-slot="collapsible-panel"]');
    if (!panel) throw new Error("Authorized clients panel is missing");
    if (panel.hasAttribute("data-starting-style")) {
      await new Promise<void>((resolve) => {
        const observer = new MutationObserver(() => {
          if (!panel.hasAttribute("data-starting-style")) { observer.disconnect(); resolve(); }
        });
        observer.observe(panel, { attributes: true });
      });
    }
    getComputedStyle(panel).height;
    await Promise.all(document.getAnimations().filter((animation) => animation.effect?.getTiming().iterations !== Infinity).map((animation) => animation.finished.catch(() => {})));
    return true;
  });
  await app.screenshot("authorized-clients");
  await expect(screen.getByText("100.64.0.2", { exact: false })).toBeVisible();
});
