import { expect } from "e2e";
import { writeFile } from "node:fs/promises";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Create PR resolves a Source remote without an owner marker", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("source-unmarked");
  const git = (args: string[]) => runPromise(run("git", args, { cwd: project }));
  await git(["remote", "add", "origin", "https://source.tanstack.com/tanstack/ai.git"]);
  await git(["fetch", "--depth", "1", "origin", "main"]);
  await git(["reset", "--hard", "origin/main"]);
  await git(["checkout", "-b", "repro-branch"]);
  await writeFile(`${project}/remote-resolution-proof.txt`, "Source remote resolution proof\n");
  await git(["add", "remote-resolution-proof.txt"]);
  await git(["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Reproduce remote resolution"]);
  await git(["init", "--bare", `${project}/../push-target.git`]);
  await git(["-C", `${project}/../push-target.git`, "config", "receive.shallowUpdate", "true"]);
  await git(["remote", "set-url", "--push", "origin", `${project}/../push-target.git`]);
  await git(["push", "-u", "origin", "repro-branch"]);
  const thread = await t3.thread({ project, title: "Source remote resolution", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByRole("button", "Create PR", { exact: true }).tap();
  await screen.getByText("Action failed", { exact: true }).waitFor();
  await browser.evaluate(async () => {
    await Promise.all(document.getAnimations().map((animation) => animation.finished.catch(() => undefined)));
    return null;
  });
  await app.screenshot("create-pr-unmarked-source-origin");
  await expect(screen.getByText(/No TanStack Source credential for source\.tanstack\.com/)).toBeVisible();
});
