import { expect } from "e2e";

import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { run } from "./shell.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test(
  "Opening the branch picker offline keeps branches available after reload",
  WEB,
  async ({ t3, app, browser, screen }) => {
    await t3.project("local-demo");
    const second = makeState(SECOND_HOME);
    // Read in a readwrite transaction so earlier app writes to the store have committed.
    const topicSaved = () =>
      browser.evaluate(async () => {
        const open = indexedDB.open("t3code:connection-runtime");
        await new Promise((resolve) => (open.onsuccess = resolve));
        const tx = open.result.transaction("vcs-refs", "readwrite");
        const all = tx.objectStore("vcs-refs").getAll();
        await new Promise((resolve) => (tx.oncomplete = resolve));
        open.result.close();
        return all.result.some((value) => String(value).includes('"name":"topic"'));
      });
    const server = startSecondServer(app.baseUrl ?? "");
    try {
      const { host, token } = await server.ready;
      const project = await second.state.project("remote-demo");
      await runPromise(run("git", ["branch", "topic"], { cwd: project }));

      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("dialog", { name: "Backend added" }).waitFor();

      await app.open("/");
      await browser.locator("[data-draft-project-trigger]").tap();
      await screen.getByRole("option", /^remote-demo\b/).tap();
      const picker = screen.getByRole("combobox", /^Branch: (From )?main/).first();
      await browser.locator('[aria-label="Branch: main"]:enabled:visible').first().waitFor();
      // Fresh refs render only after they are saved, so `topic` listed online means it is persisted.
      await picker.tap();
      await screen.getByRole("option", "topic", { exact: true }).waitFor();
      await browser.keyboard.press("Escape");
      expect(await topicSaved()).toBe(true);

      await server.stop();
      await screen.getByText(/^Scenario is (reconnecting|offline)$/).waitFor();
      await browser.reload();
      await picker.tap();
      await screen.getByRole("option", "topic", { exact: true }).waitFor();
      await browser.keyboard.press("Escape");
      await topicSaved();
      await browser.reload();
      const branchControl = screen.getByRole("combobox", /^Branch:/).first();
      await branchControl.waitFor();

      await app.screenshot("branch-picker-after-reload-with-host-offline");
      await expect(branchControl).toBeEnabled();
      await branchControl.tap();
      await screen.getByRole("option", "topic", { exact: true }).waitFor();
    } finally {
      await server.stop();
    }
  },
);
