import { expect } from "e2e";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Pull fetches a configured upstream whose tracking ref is missing", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("pull-demo");
  const git = async (...args: string[]) => (await runPromise(run("git", args, { cwd: project }))).stdout.trim();
  const remote = `${project}/../upstream.git`;
  await git("init", "--bare", "--quiet", "--initial-branch=main", remote);
  await git("remote", "add", "origin", remote);
  await git("push", "--quiet", "-u", "origin", "main");
  await git("remote", "set-head", "origin", "main");
  const original = await git("rev-parse", "HEAD");
  await git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--allow-empty", "-m", "Upstream update");
  const target = await git("rev-parse", "HEAD");
  await git("push", "--quiet", "origin", "main");
  await git("reset", "--hard", original);
  const thread = await t3.thread({ project, title: "Pull upstream update", messages: ["Start"] });
  await browser.addInitScript(() => {
    document.addEventListener("DOMContentLoaded", () => {
      const style = document.createElement("style");
      // Error descriptions include the local workspace path; redact that region in public captures.
      style.textContent = '[data-slot="toast-description"] { visibility: hidden !important; }';
      document.head.append(style);
    });
  });
  await t3.open(thread);
  await screen.getByRole("button", "Pull", { exact: true }).waitFor();
  await git("update-ref", "-d", "refs/remotes/origin/main");
  await screen.getByRole("button", "Pull", { exact: true }).tap();
  await screen.getByText(/^Pull failed$|^Pulled$/).waitFor();
  await browser.evaluate(async () => {
    await Promise.allSettled(document.getAnimations().map((animation) => animation.finished));
  });
  await app.screenshot("pull-result");
  expect(await git("rev-parse", "HEAD")).toBe(target);
});
