import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { startSecondServer } from "./second-server.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Saved environment recovers after its network listener crashes", WEB, async ({t3, app, screen, browser}) => {
  await t3.project("demo");
  const server = startSecondServer(app.baseUrl ?? "");
  try {
    const {host, token} = await server.ready;
    await t3.open("/settings/connections");
    await screen.getByRole("button", "Add environment").tap();
    const dialog = screen.getByRole("dialog");
    await dialog.getByPlaceholder("backend.example.com").fill(host);
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button", "Add environment").tap();
    await screen.getByRole("button", "More actions for Scenario").waitFor();
    await browser.addInitScript(() => {
      let online = false;
      let registrations = 0;
      Object.defineProperty(navigator, "onLine", {get: () => online, configurable: true});
      const add = window.addEventListener.bind(window);
      window.addEventListener = ((type: string, ...args: unknown[]) => {
        if (type === "online" && ++registrations === 5) throw new Error("Injected network listener crash");
        return (add as (...args: unknown[]) => void)(type, ...args);
      }) as typeof window.addEventListener;
      (window as any).restoreNetwork = () => { online = true; window.dispatchEvent(new Event("online")); };
    });
    await app.open("/settings/connections");
    await screen.getByText("This device is offline", {exact: false}).first().waitFor();
    await app.screenshot("1-offline-after-listener-crash");
    await browser.evaluate(() => (window as any).restoreNetwork());
    await runPromise(Effect.sleep("30 seconds"));
    await app.screenshot("2-thirty-seconds-after-network-returns");
    await expect(screen.getByText("This device is offline", {exact: false})).toBeHidden();
  } finally { await server.stop(); }
});
