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

const api = (endpoint: string, method = "GET", body?: unknown) => JSON.parse(execFileSync("glab", ["api", endpoint, "--method", method, ...(body ? ["--input", "-"] : [])], { input: body ? JSON.stringify(body) : undefined, encoding: "utf8" }) || "null");
const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
async function mergeable(id: number, iid: number, conflicting: boolean) {
  for (let i = 0; i < 60; i++) {
    const mr = api(`projects/${id}/merge_requests/${iid}?with_merge_status_recheck=true`);
    if (conflicting ? mr.has_conflicts === true : mr.detailed_merge_status === "mergeable") return;
    await pause(1000);
  }
  throw new Error("GitLab did not compute the requested merge state");
}

test("A refused merge refreshes the open detail panel to conflicting", WEB, async ({ t3, app, browser, screen }) => {
  const remote = api("projects", "POST", { name: `t3-proof-41500-${Date.now()}`, visibility: "private", initialize_with_readme: true, default_branch: "main" });
  try {
    const commit = (branch: string, content: string, action: string, start?: string) => api(`projects/${remote.id}/repository/commits`, "POST", { branch, ...(start ? { start_branch: start } : {}), commit_message: "Synthetic conflict fixture", actions: [{ action, file_path: "notes.txt", content }] });
    commit("main", "line one\nline two\nline three\n", "create");
    commit("a", "line one\nchange from a\nline three\n", "update", "main");
    commit("b", "line one\nchange from b\nline three\n", "update", "main");
    const a = api(`projects/${remote.id}/merge_requests`, "POST", { source_branch: "a", target_branch: "main", title: "First change" });
    const b = api(`projects/${remote.id}/merge_requests`, "POST", { source_branch: "b", target_branch: "main", title: "Conflicting second change" });
    await mergeable(remote.id, a.iid, false);
    await mergeable(remote.id, b.iid, false);
    const workspace = await t3.project("Merge refusal demo");
    execFileSync("git", ["remote", "add", "origin", remote.http_url_to_repo], { cwd: workspace });
    await t3.thread({ project: workspace, title: "Merge refusal proof", messages: ["Start"] });
    await browser.setViewport({ width: 1280, height: 800 });
    await t3.open("/pull-requests");
    await screen.getByText("Conflicting second change", { exact: true }).tap();
    const merge = screen.getByRole("button", "Merge", { exact: true });
    await merge.waitFor();
    await app.screenshot("before-host-conflict");
    api(`projects/${remote.id}/merge_requests/${a.iid}/merge`, "PUT");
    await mergeable(remote.id, b.iid, true);
    await merge.tap();
    await screen.getByRole("button", "Confirm merge?", { exact: true }).tap();
    await screen.getByText(/Could not merge this merge request/).waitFor();
    await pause(30000);
    await app.screenshot("after-refused-merge");
    await expect(screen.getByRole("button", "Resolve conflicts", { exact: true })).toBeVisible();
  } finally {
    api(`projects/${remote.id}`, "DELETE");
  }
});
