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

const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

test("Retry reconnects a saved T3 Connect environment after Clerk was unreachable at launch", WEB, async ({t3, app, screen, browser}) => {
  await t3.project("Recovery demo");
  await t3.open("/settings/connections");
  await screen.getByRole("button", "Sign in to T3 Connect").tap();
  await screen.getByRole("textbox", "Email address").fill(process.env.FACTORY_USER_1_EMAIL!);
  await screen.getByRole("button", "Continue", {exact:true}).tap();
  await browser.locator('input[name="password"]').fill(process.env.FACTORY_USER_1_PASSWORD!);
  await Promise.all([
    browser.waitForResponse("**/prepare_second_factor*"),
    screen.getByRole("button", "Continue", {exact:true}).tap(),
  ]);
  await browser.locator('input[autocomplete="one-time-code"]').fill(process.env.FACTORY_CLERK_EMAIL_CODE!);
  await browser.locator('//p[text()="Recovery demo host"]/ancestor::div[3]').getByRole("button", "Add", {exact:true}).tap();
  // Wait for a working relay before the failed launch, without classifying setup as the bug.
  await browser.locator('text="T3 Connect · Connected"').waitFor({state:"visible", timeout:60000});
  let blocked = true;
  await browser.route(/https:\/\/[^/]*(?:accounts\.dev|clerk\.com)\//, async route => blocked ? route.abort() : route.continue());
  await browser.route(/https:\/\/relay-factory\.t3\.codes\//, async route => blocked ? route.abort() : route.continue());
  await app.restart();
  await app.open("/settings/connections");
  await pause(30000);
  await app.screenshot("launched-with-clerk-unreachable");
  blocked = false;
  await pause(70000);
  await screen.getByRole("button", "Details", {exact:true}).first().tap();
  await screen.getByRole("button", "Retry now", {exact:true}).tap();
  await pause(15000);
  // On the fix Retry reloads, closing Details. Reopen it only if the first retry did not recover.
  const connected = await browser.evaluate(() => document.body.innerText.includes("T3 Connect · Connected"));
  if (!connected) {
    await screen.getByRole("button", "Retry now", {exact:true}).tap();
    await pause(15000);
  }
  await app.screenshot("after-network-restored-and-retry");
  await expect(screen.getByText("T3 Connect · Connected", {exact:false})).toBeVisible({timeout:30000});
});
