/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Connect retries reuse a pairing credential before redemption", WEB, async ({t3, app, screen, browser}) => {
  await t3.project("Pairing retry demo");
  await browser.addInitScript(() => {
    // Redact unrelated shared test-account machine labels in recordings.
    const redact = () => document.querySelectorAll('p,span').forEach(e => {
      if (/^f-[a-f0-9]{8}-[a-z0-9]+$/.test(e.textContent ?? '')) (e as HTMLElement).style.visibility='hidden';
    });
    new MutationObserver(redact).observe(document,{childList:true,subtree:true});
    const original = window.fetch.bind(window);
    const state = { bootstraps: 0, descriptors: 0, blocked: true };
    Object.assign(window, { pairingProof: state });
    window.fetch = async (...args) => {
      const url = String(args[0] instanceof Request ? args[0].url : args[0]);
      if (url.includes("t3coderelay.com") && url.includes("/.well-known/t3/environment")) {
        state.descriptors++;
        if (state.blocked) throw new TypeError("Failed to fetch");
      }
      const result = await original(...args);
      if (url.includes("relay-factory.t3.codes/v1/environments/") && url.endsWith("/connect") && result.ok) state.bootstraps++;
      return result;
    };
  });
  await t3.open("/settings/connections");
  await screen.getByRole("button", "Sign in to T3 Connect").waitFor({timeout:60000});
  await screen.getByRole("button", "Sign in to T3 Connect").tap();
  await browser.locator('input[name="identifier"]').waitFor();
  await browser.evaluate(async (credentials) => {
    const clerk=(window as any).Clerk;
    const signIn=await clerk.client.signIn.create({identifier:credentials.email,password:credentials.password});
    const factor=signIn.supportedSecondFactors.find((f:any)=>f.strategy==='email_code');
    await signIn.prepareSecondFactor({strategy:'email_code',emailAddressId:factor.emailAddressId});
    const result=await signIn.attemptSecondFactor({strategy:'email_code',code:credentials.code});
    await clerk.setActive({session:result.createdSessionId});
    clerk.closeSignIn();
  }, {email:process.env.FACTORY_USER_1_EMAIL!,password:process.env.FACTORY_USER_1_PASSWORD!,code:process.env.FACTORY_CLERK_EMAIL_CODE!});
  await screen.getByRole("button", "Not now", {exact:true}).tap();
  await screen.getByRole("button", "Done", {exact:true}).tap();
  await screen.getByText("List", {exact:true}).tap();
  await browser.locator('div.sm\\:justify-between:has(p:text-is("Pairing proof host")) button').tap();
  await screen.getByText(/This device can't reach/).first().waitFor({timeout:60000});
  await browser.evaluate(async () => {
    const s=(window as any).pairingProof;
    await new Promise<void>(resolve => {const i=setInterval(()=>{if(s.descriptors>=3){clearInterval(i);resolve();}},100);});
  });
  await app.screenshot("unreachable-tunnel-retries");
  const counts=await browser.evaluate(() => (window as any).pairingProof);
  expect(counts.bootstraps, "Three descriptor failures must reuse one unredeemed bootstrap").toBe(1);
  await browser.evaluate(() => { (window as any).pairingProof.blocked=false; });
  await screen.getByText("T3 Connect · Connected", {exact:false}).waitFor({timeout:60000});
  await app.screenshot("same-session-recovered");
});
