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

const fixture = {"upstream": "https://gitlab.com/julius54/t3-pr23439-proof-1794643701.git", "plain": "https://gitlab.com/juliusmarminge/t3-pr23439-proof-1794643701.git", "nested": "https://gitlab.com/juliusmarminge/pr23439-proof-1794643701/renamed-fork-1794643701.git", "ids": [88928292, 88928295, 88928296], "group": 147550953};
const api = (path: string, args: string[] = []) => JSON.parse(execFileSync("glab", ["api", path, ...args], { encoding: "utf8" }));

test("Create MR from plain and nested renamed GitLab forks", WEB, async ({t3, app, screen, browser}) => {
  for (const mr of api(`projects/${fixture.ids[0]}/merge_requests?state=opened`)) {
    api(`projects/${fixture.ids[0]}/merge_requests/${mr.iid}`, ["--method", "PUT", "-f", "state_event=close"]);
  }
  const cases = [
    {name:"Plain fork", branch:"fork-feature", remote:"plain"},
    {name:"Nested renamed fork", branch:"nested-feature", remote:"nested"},
    {name:"Same project control", branch:"control-feature", remote:"origin"},
  ];
  const seeded = [];
  for (const item of cases) {
    const project = await t3.project(item.name.replaceAll(" ", "-"));
    const git = (...args: string[]) => execFileSync("git", args, {cwd: project, encoding:"utf8", stdio:["ignore","pipe","pipe"]});
    git("remote", "add", "origin", fixture.upstream);
    git("remote", "add", "plain", fixture.plain);
    git("remote", "add", "nested", fixture.nested);
    git("fetch", "origin");
    git("reset", "--hard", "origin/main");
    git("checkout", "-b", item.branch);
    writeFileSync(`${project}/feature.txt`, `${item.name} feature\n`);
    git("add", ".");
    git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", `Add ${item.name} feature`);
    git("push", "--force", "-u", item.remote, item.branch);
    const thread = await t3.thread({project, title:item.name, messages:[]});
    seeded.push({...item, thread});
  }
  const results = [];
  for (const item of seeded) {
    await t3.open(item.thread);
    await screen.getByRole("button", "Create MR", {exact:true}).tap();
    await screen.getByText(/^(Created MR|Action failed)$/).first().waitFor({timeout:180_000});
    await browser.evaluate(async () => { await Promise.all(document.getAnimations().filter(a => a.effect?.getTiming().iterations !== Infinity).map(a => a.finished.catch(() => {}))); });
    await app.screenshot(item.branch);
    results.push(api(`projects/${fixture.ids[0]}/merge_requests?state=opened&source_branch=${item.branch}`));
  }
  await expect(results.map((mrs) => mrs.length)).toEqual([1,1,1]);
  await expect(results.map((mrs) => mrs[0]?.target_project_id)).toEqual([fixture.ids[0],fixture.ids[0],fixture.ids[0]]);
  await expect(results.map((mrs) => mrs[0]?.source_project_id)).toEqual([fixture.ids[1],fixture.ids[2],fixture.ids[0]]);
});
