import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { WS_METHODS } from "@t3tools/contracts";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Recognize an existing GitLab merge request from a fork", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("Fork merge request");
  const git = (...args: string[]) => execFileSync("git", args, { cwd: project, encoding: "utf8" });
  git("remote", "add", "origin", "https://gitlab.com/juliusmarminge/proof-40894-fork-mr.git");
  git("remote", "add", "fork", "https://gitlab.com/julius54/proof-40894-fork-mr.git");
  git("fetch", "origin", "main");
  git("fetch", "fork", "feature/x");
  git("checkout", "-B", "main", "origin/main");
  git("checkout", "-b", "feature/x", "--track", "fork/feature/x");
  const thread = await t3.thread({ project, title: "Find the existing fork MR", messages: ["Check this fork branch"] });
  await t3.open(thread);
  await screen.getByRole("combobox", "Branch: feature/x").waitFor();
  // Exercise the same create action even when discovery already found the MR.
  const result = await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    return yield* client[WS_METHODS.gitRunStackedAction]({
      cwd: project, action: "create_pr", actionId: crypto.randomUUID(),
    }).pipe(Stream.runCollect, Effect.result);
  }).pipe(Effect.scoped));
  const reused = result._tag === "Success" && result.success.some((event) => event.kind === "action_finished" && event.result.pr.status === "opened_existing");
  console.log("Create MR action reused existing MR:", reused);
  await screen.getByText("Syncing messages...", { exact: false }).waitFor({ state: "hidden" });
  await app.screenshot("fork-mr-status");
  const create = screen.getByRole("button", "Create MR", { exact: true });
  if (await create.count() > 0) {
    await create.tap();
    await screen.getByText("Action failed", { exact: false }).first().waitFor({ timeout: 60000 });
  } else {
    await screen.getByRole("button", /Merge request #1/).tap();
    await screen.getByText("Recognize existing fork merge request", { exact: true }).first().waitFor();
  }
  await app.screenshot("fork-mr-action");
  await expect(screen.getByRole("link", /MR #1 - Open/)).toBeVisible({ timeout: 30000 });
  expect(reused).toBe(true);
});
