import { execFileSync } from "node:child_process";
import { writeFileSync } from "node:fs";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB, makeState } from "./t3.ts";

const command = (name: string, args: string[], cwd?: string) => execFileSync(name, args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
const api = (args: string[]) => JSON.parse(command("glab", ["api", ...args]));

test("Merging Thread A's linked MR keeps unrelated Local Thread B active", WEB, async ({ t3, app, screen, browser }) => {
  const repo = api(["projects", "--method", "POST", "-f", `name=settlement-proof-${Date.now()}`, "-f", "visibility=private", "-f", "initialize_with_readme=false"]);
  try {
    const project = await t3.project("Merge ownership demo", { "README.md": "# Merge ownership demo\n" });
    const git = (...args: string[]) => command("git", args, project);
    git("remote", "add", "origin", repo.http_url_to_repo);
    git("push", "-u", "origin", "main");
    git("checkout", "-b", "feat/example");
    writeFileSync(`${project}/example.txt`, "Example feature\n");
    git("add", ".");
    git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Add example feature");
    git("push", "-u", "origin", "feat/example");
    const mr = api([`projects/${repo.id}/merge_requests`, "--method", "POST", "-f", "source_branch=feat/example", "-f", "target_branch=main", "-f", "title=Example feature"]);
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      yield* client["server.updateSettings"]({ patch: { sidebarAutoSettleOnMerge: true, sidebarAutoSettleAfterDays: null } });
    }).pipe(Effect.scoped));
    const a = await t3.thread({ project, title: "Repo Thread A", messages: ["Prepare example feature"] });
    const b = await t3.thread({ project, title: "Repo Thread B", messages: ["Inspect example feature"] });
    await t3.open(a);
    await screen.getByRole("textbox", "Message Repo Thread A").waitFor();
    await browser.keyboard.press("Control+k");
    await screen.getByRole("dialog", "Command palette").getByRole("combobox").fill("Link pull request to thread");
    await screen.getByRole("option", "Link pull request to thread").tap();
    await screen.getByPlaceholder("Pull request URL or #42").fill(mr.web_url);
    await screen.getByRole("button", "Link", { exact: true }).tap();
    await screen.getByRole("button", "Merge", { exact: true }).waitFor({ timeout: 60000 });
    await app.screenshot("before-merge");
    await screen.getByRole("button", "Merge", { exact: true }).tap();
    await screen.getByRole("alertdialog").getByRole("button", "Merge", { exact: true }).tap();
    // Allow the real merge notification and branch re-check to finish on both revisions.
    await browser.evaluate(async () => { await new Promise(resolve => setTimeout(resolve, 15000)); return null; });
    const settled = screen.getByRole("button", "Settled", { exact: false });
    if (await settled.isVisible()) await settled.tap();
    await screen.getByRole("button", "Repo Thread B", { exact: false }).waitFor();
    await browser.evaluate(async () => { await new Promise(resolve => setTimeout(resolve, 1000)); return null; });
    await app.screenshot("after-merge");
    const listed = JSON.parse((await runPromise(makeState(T3_HOME).cli(["thread", "list", "--project", project, "--json"]))).stdout);
    const threads = Array.isArray(listed) ? listed : listed.threads;
    expect(threads.find((t: { threadId?: string; id?: string }) => (t.threadId ?? t.id) === b.threadId)?.settled, "Unlinked Local Thread B remains active after Thread A's MR merges").toBe(false);
  } finally {
    api([`projects/${repo.id}`, "--method", "DELETE"]);
  }
});
