import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Pairing this server refuses its own environment ID without consuming the code", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("Pairing demo");
  await browser.addInitScript(() => {
    Object.defineProperty(navigator, "clipboard", { value: {
      writeText: async (value: string) => { (window as any).__copied = value; },
    }});
  });
  await t3.open("/settings/access");
  await screen.getByRole("button", "Create link", { exact: true }).tap();
  await screen.getByRole("dialog").getByRole("button", "Create link", { exact: true }).tap();
  await screen.getByRole("button", "Copy code", { exact: true }).tap();
  const code = await browser.evaluate(() => (window as any).__copied as string);
  await app.open("/settings/connections");
  await screen.getByRole("button", "Add environment", { exact: true }).tap();
  await screen.getByLabel("Host", { exact: true }).fill(app.baseUrl!);
  await screen.getByLabel("Pairing code", { exact: true }).fill(code);
  await screen.getByRole("dialog").getByRole("button", "Add environment", { exact: true }).tap();
  // Capture either the refusal or the false success, without branching the reproduction.
  await browser.locator('text=/Backend added|That address reports this machine/').first().waitFor({ state: "visible" });
  await browser.evaluate(async () => {
    await Promise.all(document.getAnimations().filter(a => a.effect?.getComputedTiming().iterations !== Infinity).map(a => a.finished.catch(() => {})));
  });
  const refused = await browser.evaluate(() => document.body.innerText.includes("That address reports this machine's own environment ID"));
  await app.screenshot("pairing-result");
  await browser.keyboard.press("Escape");
  await app.open("/settings/connections");
  await expect(screen.getByText("No saved remote environments", { exact: true })).toBeVisible();
  await app.open("/settings/access");
  await screen.getByRole("button", "Create link", { exact: true }).waitFor({ state: "visible" });
  await browser.evaluate(async () => {
    await Promise.all(document.getAnimations().filter(a => a.effect?.getComputedTiming().iterations !== Infinity).map(a => a.finished.catch(() => {})));
  });
  await app.screenshot("unused-pairing-link");
  await expect(refused).toBe(true);
  await expect(screen.getByText("1 client · 1 pairing link", { exact: true })).toBeVisible();
});
