/// <reference lib="dom" />
import { writeFileSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { CommandId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";
const command = (bin: string, args: string[], cwd?: string) => execFileSync(bin, args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
const api = (path: string, fields: string[] = [], method = "POST") => JSON.parse(command("glab", ["api", path, "--method", method, ...fields.flatMap(f => ["-f", f])]) || "null");
test("Linked MR indicators agree with newly fetched merged detail", WEB, async ({t3, app, browser, screen}) => {
 const remote = api("projects", [`name=linked-status-${Date.now()}`, "visibility=private", "initialize_with_readme=false"]);
 const project = await t3.project("demo", {"README.md": "Release notes demo", ".git/config": `[core]\nrepositoryformatversion = 0\n[remote "origin"]\nurl = ${remote.http_url_to_repo}\nfetch = +refs/heads/*:refs/remotes/origin/*\n`});
 try {
  const git = (...args: string[]) => command("git", args, project);
  git("push", "-u", "origin", "main");
  git("checkout", "-b", "notes");
  writeFileSync(`${project}/RELEASE.md`, "Release notes ready.\n");
  git("add", "RELEASE.md");
  git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Publish release notes");
  git("push", "-u", "origin", "notes");
  git("checkout", "main");
  const mr = api(`projects/${remote.id}/merge_requests`, ["source_branch=notes", "target_branch=main", "title=Publish release notes"]);
  const thread = await t3.thread({project, title:"Linked changes", messages:["Start"]});
  await runPromise(Effect.gen(function*(){
   const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
   const key = {threadId:ThreadId.make(thread.threadId), host:"gitlab.com", repository:remote.path_with_namespace, number:mr.iid};
   yield* client["orchestration.dispatchCommand"]({type:"thread.pull-request.link", commandId:CommandId.make(`${thread.threadId}-link`), ...key, url:mr.web_url, source:"manual"});
   yield* client["orchestration.dispatchCommand"]({type:"thread.pull-request-link.sync", commandId:CommandId.make(`${thread.threadId}-sync`), ...key, snapshot:{state:"open", title:mr.title, headBranch:mr.source_branch, baseBranch:mr.target_branch, isDraft:false, updatedAt:mr.updated_at, syncedAt:new Date().toISOString()}, stack:null});
  }).pipe(Effect.scoped));
  await browser.setViewport({width:1440,height:900});
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel", {exact:true}).tap();
  await screen.getByRole("button", "Linked items L", {exact:true}).tap();
  await screen.getByRole("link", new RegExp(`^#${mr.iid} Publish release notes`)).waitFor();
  await app.screenshot("initial-open-linked-mr");
  await screen.getByRole("link", new RegExp(`^#${mr.iid} Publish release notes`)).tap();
  await screen.getByRole("button", "Merge", {exact:true}).waitFor();
  await screen.getByText("No comments yet.", {exact:true}).waitFor();
  api(`projects/${remote.id}/merge_requests/${mr.iid}/merge`, [], "PUT");
  await t3.open(thread);
  await t3.open(`/pull-requests?${new URLSearchParams({state:"merged", repository:remote.path_with_namespace})}`);
  await screen.getByRole("button", new RegExp(`^Merged #${mr.iid} Publish release notes`)).tap();
  await screen.getByText("Merged", {exact:true}).waitFor({timeout:30000});
  await screen.getByText("No comments yet.", {exact:true}).waitFor();
  await screen.getByRole("button", "Linked changes, demo", {exact:true}).tap();
  await screen.getByText("Merged", {exact:true}).waitFor({timeout:30000});
  await screen.getByText("No comments yet.", {exact:true}).waitFor();
  const icon = browser.locator('[data-active-tab="true"] svg.lucide-git-merge');
  await icon.waitFor({timeout:2000}).catch(()=>{});
  await screen.getByRole("button", "More merge request actions", {exact:true}).waitFor();
  await screen.getByRole("textbox", "Message Linked changes", {exact:true}).hover();
  await app.screenshot("merged-detail-and-thread-indicators");
  const tabMerged = await icon.isVisible();
  await screen.getByRole("button", "Linked items", {exact:true}).tap();
  await app.screenshot("linked-items-after-real-merge");
  const count = await screen.getByText("0 open · 1 linked", {exact:false}).isVisible();
  expect(tabMerged, "Tab icon follows merged detail").toBe(true);
  expect(count, "Linked items open count follows merged detail").toBe(true);
 } finally { try { api(`projects/${remote.id}`, [], "DELETE"); } catch {} }
});
