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

test("First machine switch uses the destination workspace default", WEB, async ({ t3, app, screen, browser }) => {
  const primary = await t3.project("demo");
  const git = (cwd: string, args: string[]) => runPromise(run("git", args, { cwd }));
  await git(primary, ["remote", "add", "origin", "https://github.com/scenario/demo.git"]);
  const server = startSecondServer(app.baseUrl ?? "");
  try {
    const { host, token } = await server.ready;
    const destination = await makeState(SECOND_HOME).state.project("demo", {"t3.json": '{"defaultThreadEnvMode":"worktree"}'});
    await git(destination, ["remote", "add", "origin", "https://github.com/scenario/demo.git"]);
    await git(destination, ["branch", "-m", "remote-base"]);
    await t3.open();
    await screen.getByRole("textbox").fill("Plan the next change");
    const draftUrl = await browser.evaluate(() => location.href);
    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", "List", { exact: true }).tap();
    await screen.getByRole("button", "More actions for Scenario").waitFor({ timeout: 60_000 });
    await app.open(draftUrl);
    await screen.getByText("Scenario").last().tap();
    const machine = (index: number) => browser.locator('[role="menuitemradio"]').nth(index);
    const target = (await machine(0).getAttribute("aria-checked")) === "true" ? 1 : 0;
    await machine(target).click();
    await screen.getByRole("combobox", /Branch: .*remote-base/).first().waitFor();
    await new Promise(resolve => setTimeout(resolve, 4000));
    await app.screenshot("destination-workspace-default");
    await expect(screen.getByRole("combobox", "Workspace")).toContainText("New worktree");
  } finally { await server.stop(); }
});
