import { execFileSync } from "node:child_process";
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 api = (...args: string[]) => execFileSync("glab", ["api", ...args], { encoding: "utf8" });
test("A refused GitLab comment shows the action fallback without an internal prefix", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Comment failure proof");
  execFileSync("git", ["remote", "add", "origin", "https://gitlab.com/julius54/t3-proof-49151.git"], { cwd: project });
  const thread = await t3.thread({ project, title: "Comment failure proof", messages: ["Ready"], model: "multi-turn" });
  const projectId = await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    const { projects } = yield* client["orchestration.getArchivedShellSnapshot"]({});
    const id = projects.find((entry) => entry.workspaceRoot === project)?.id;
    if (!id) throw new Error("Fixture project missing");
    return id;
  }).pipe(Effect.scoped));
  const issue = JSON.parse(api("--method", "POST", "projects/89894939/issues", "--field", "title=Locked issue (repro 49151)"));
  try {
    await t3.open(thread);
    await t3.open(`/issues?selectedProjectId=${projectId}&tracker=gitlab&scope=julius54/t3-proof-49151&key=${issue.iid}`);
    const composer = screen.getByPlaceholder("Leave a comment", { exact: true });
    await composer.waitFor({ timeout: 60_000 });
    api("--method", "DELETE", `projects/89894939/issues/${issue.iid}`);
    await composer.fill("Please reopen");
    await screen.getByRole("button", "Comment", { exact: true }).tap();
    await screen.getByText("The comment could not be posted", { exact: true }).waitFor();
    await browser.evaluate(async () => {
      await Promise.all(document.getAnimations().filter((animation) => animation.effect?.getComputedTiming().iterations !== Infinity).map((animation) => animation.finished.catch(() => {})));
      return null;
    });
    await app.screenshot("comment-refused-toast");
    await expect(screen.getByText("The tracker refused it.", { exact: true })).toBeVisible();
  } finally {
    try { api("--method", "DELETE", `projects/89894939/issues/${issue.iid}`); } catch {}
  }
});
