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

test("Earlier merged features stay separate from the later promotion", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("Release");
  const git = (...args: string[]) => execFileSync("git", args, {cwd:project, encoding:"utf8"}).trim();
  const api = (path: string, method = "GET", fields: Record<string,string> = {}) => JSON.parse(execFileSync("glab", ["api", path, "--method", method, ...Object.entries(fields).flatMap(([k,v])=>["-f",`${k}=${v}`])], {encoding:"utf8"}));
  const name = `stack-chronology-proof-${Date.now()}`;
  const repo = api("projects", "POST", {name, visibility:"private", initialize_with_readme:"false"});
  try {
    git("config","user.name","Scenario"); git("config","user.email","scenario@example.invalid");
    git("remote","add","origin",repo.http_url_to_repo);
    git("push","-u","origin","main");
    git("switch","-c","staging"); git("push","-u","origin","staging");
    for (const n of [1,2]) {
      git("switch","-c",`feature-${n}`,"staging");
      writeFileSync(`${project}/feature-${n}.txt`, `Feature ${n}\n`);
      git("add","."); git("commit","-m",`feature ${n}`); git("push","-u","origin",`feature-${n}`);
      api(`projects/${repo.id}/merge_requests`,"POST",{source_branch:`feature-${n}`,target_branch:"staging",title:`feature ${n}`});
    }
    git("switch","staging");
    const thread = await t3.thread({project,title:"Promote staging",messages:["Review the release"]});
    await t3.open(thread);
    await screen.getByRole("textbox", "Message Promote staging", {exact:true}).waitFor();
    await screen.getByRole("combobox", "Branch: staging", {exact:true}).waitFor();
    const link = async (n:number) => {
      await browser.keyboard.press("Control+k");
      await screen.getByRole("dialog").getByRole("combobox").fill("> Link pull request to thread");
      await screen.getByRole("dialog").getByText("Link pull request to thread", {exact:true}).tap();
      await browser.locator('input[placeholder="Pull request URL or #42"]').fill(`${repo.web_url}/-/merge_requests/${n}`);
      await screen.getByRole("button","Link",{exact:true}).tap();
      await screen.getByRole("dialog", "Link pull request",{exact:true}).waitFor({state:"hidden"});
    };
    await link(1); await link(2);
    const merge = (n:number) => {
      for (let attempt=0; attempt<30; attempt++) {
        const mr = api(`projects/${repo.id}/merge_requests/${n}?with_merge_status_recheck=true`);
        if (mr.detailed_merge_status === "mergeable") return api(`projects/${repo.id}/merge_requests/${n}/merge`,"PUT",{should_remove_source_branch:"false"});
        if (attempt === 29) throw new Error(`GitLab MR ${n} not ready: ${mr.detailed_merge_status}`);
      }
    };
    merge(1); merge(2);
    git("pull","--ff-only");
    api(`projects/${repo.id}/merge_requests`,"POST",{source_branch:"staging",target_branch:"main",title:"promote staging"});
    await link(3);
    merge(3);
    // Reopening each real MR link refreshes its terminal snapshot through the app's service.
    await link(1); await link(2); await link(3);
    await t3.open(thread);
    await screen.getByRole("region", "Version Control",{exact:true}).waitFor();
    await screen.getByRole("button", "Show 2 more", {exact:true}).tap();
    for (const [n,title] of [[1,"feature 1"],[2,"feature 2"],[3,"promote staging"]] as const) {
      await screen.getByRole("button", `Merge request #${n}, merged: ${title}`, {exact:true}).waitFor();
    }
    await app.screenshot("all-three-merged-entries");
    await screen.getByRole("button", "Show less", {exact:true}).tap();
    await app.screenshot("merged-promotion-current-pr");
    expect(await screen.getByRole("button","Merge request #3, merged: promote staging",{exact:true}).isVisible()).toBe(true);
  } finally {
    api(`projects/${repo.id}`, "DELETE");
  }
});
