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

test("A fully pushed feature branch offers Create PR before the first message", IOS, async ({ t3, app, screen }) => {
  const project = await t3.project("Pushed feature");
  const git = (...args: string[]) => execFileSync("git", args, { cwd: project, encoding: "utf8" });
  const branch = `proof38182-${Date.now()}`;
  git("remote", "add", "origin", "https://github.com/juliusmarminge/acme-corp-lib.git");
  git("fetch", "--depth=1", "origin", "main");
  git("checkout", "-B", "main", "origin/main");
  git("remote", "set-head", "origin", "main");
  git("checkout", "-b", branch);
  writeFileSync(`${project}/proof-feature.txt`, "Synthetic feature for mobile Create PR proof.\n");
  git("add", "proof-feature.txt");
  git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Add synthetic proof feature");
  git("push", "--set-upstream", "origin", branch);
  try {
    await t3.open();
    await screen.getByRole("button", "New chat").tap();
    await screen.getByRole("textbox", "Search projects").waitFor({ state: "visible" });
    await screen.getByRole("button", "Pushed feature").tap();
    await screen.getByRole("textbox", "Ask anything").waitFor({ state: "visible" });
    if (await screen.getByRole("button", "New worktree").isVisible()) {
      await screen.getByRole("button", "New worktree").tap();
    }
    await screen.getByRole("button", /^Branch:/).tap();
    await screen.getByRole("textbox", "Find a branch").waitFor({ state: "visible" });
    await screen.getByText(branch, { exact: true }).first().tap();
    await screen.getByRole("button", "Git controls").tap();
    await screen.getByText("Clean", { exact: true }).waitFor({ state: "visible" });
    await app.screenshot("fully-pushed-git-controls");
    await expect(screen.getByText("Create PR", { exact: true })).toBeEnabled();
  } finally {
    git("push", "origin", "--delete", branch);
  }
});
