import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import { IOS, test } from "./t3-mobile.ts";

test("A mixed setting can be turned off after an older environment drops it", IOS, async ({ t3, app, screen, device }) => {
  await t3.project("Switch proof");
  await t3.open();
  await screen.getByTestId("workspace-tab-settings").waitFor({ state: "visible", timeout: 120000 });
  const older = process.env.PROOF_OLDER_CHECKOUT!;
  const origin = process.env.PROOF_OLDER_ORIGIN!;
  const output = execFileSync(process.execPath, ["apps/server/src/bin.ts", "auth", "pairing", "create", "--ttl", "15m", "--label", "proof", "--base-url", origin, "--base-dir", `${older}/.t3`], { cwd: older, encoding: "utf8" });
  const pairingUrl = /Pair URL:\s*(\S+)/.exec(output)![1];
  const query = new URLSearchParams({ pairingUrl, autoConnect: "1" });
  await device.openLink(`t3code-dev://connections/new?${query}`, { app: "com.t3tools.t3code.dev" });
  await device.alert("accept").catch(() => {});
  await screen.getByTestId("workspace-tab-settings").waitFor({ state: "visible", timeout: 120000 });
  await device.openLink("t3code-dev://settings/source-control", { app: "com.t3tools.t3code.dev" });
  await device.alert("accept").catch(() => {});
  for (let i = 0; i < 4; i++) await screen.swipe({ direction: "down", momentum: "fast" });
  await screen.scrollUntilVisible(screen.getByRole("switch", "Clone into host folders"));
  await screen.getByRole("switch", "Clone into host folders").tap();
  const mixed = screen.getByRole("button", /Set Clone into host folders (on|off) for selected environments/);
  await screen.scrollUntilVisible(mixed);
  for (let i = 0; i < 4; i++) await screen.swipe({ direction: "down", momentum: "fast" });
  await app.screenshot("mixed-after-on");
  await mixed.tap();
  await screen.scrollUntilVisible(screen.getByText("Clones", { exact: true }));
  for (let i = 0; i < 4; i++) await screen.swipe({ direction: "down", momentum: "fast" });
  await app.screenshot("after-off");
  await expect(screen.getByRole("switch", "Clone into host folders")).toBeVisible();
  await expect(screen.getByRole("switch", "Clone into host folders")).not.toBeChecked();
});
