import { writeFakeCli } from "@t3tools/provider-testing/fakeCli";
import { expect } from "e2e";
import * as Effect from "effect/Effect";

import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test(
  "A branch tracking a local branch finds its fork merge request",
  WEB,
  async ({ t3, app, screen }) => {
    const project = await t3.project("demo", {
      "t3.json": JSON.stringify({ defaultThreadEnvMode: "local" }),
    });
    const git = (...args: string[]) => runPromise(run("git", args, { cwd: project }));
    const upstream = `${project}-upstream.git`;
    const fork = `${project}-fork.git`;
    const branch = "feature/local-track";
    await git("init", "--bare", upstream);
    await git("init", "--bare", fork);
    await git("remote", "add", "origin", "git@gitlab.scenario.invalid:example/demo.git");
    await git("remote", "add", "fork", "git@gitlab.scenario.invalid:alice/demo.git");
    const localSsh = writeFakeCli({
      directory: `${project}/../bin`,
      name: "local-git-ssh",
      source: `const { spawnSync } = await import("node:child_process");
        const [command, path] = process.argv.at(-1).split(" ");
        const repository = path.includes("alice") ? ${JSON.stringify(fork)} : ${JSON.stringify(upstream)};
        const result = spawnSync(command, [repository], { stdio: "inherit" });
        process.exit(result.status ?? 1);`,
    });
    await git("config", "ssh.variant", "simple");
    await git("config", "core.sshCommand", JSON.stringify(localSsh));
    await git("push", "-u", "origin", "main");
    await git("checkout", "-b", branch, "--track", "main");
    await git(
      "-c",
      "user.name=Scenario",
      "-c",
      "user.email=scenario@example.invalid",
      "commit",
      "--allow-empty",
      "-m",
      "Fork feature",
    );
    await git("push", "fork", branch);

    const mergeRequest = {
      iid: 42,
      title: "Fork feature",
      state: "opened",
      web_url: "https://gitlab.scenario.invalid/example/demo/-/merge_requests/42",
      source_branch: branch,
      target_branch: "main",
      source_project_id: 2,
      target_project_id: 1,
    };
    writeFakeCli({
      directory: `${T3_HOME}/bin`,
      name: "glab",
      source: `
        const args = process.argv.slice(2);
        const [command, subcommand] = args;
        if (command === "mr" && subcommand === "list") {
          const at = args.indexOf("--source-branch");
          console.log(JSON.stringify(args[at + 1] === ${JSON.stringify(branch)} ? [${JSON.stringify(mergeRequest)}] : []));
        } else if (command === "api" && subcommand === "projects/2") {
          console.log(JSON.stringify({ path_with_namespace: "alice/demo" }));
        } else if (command === "api" && subcommand === "projects/1") {
          console.log(JSON.stringify({ path_with_namespace: "example/demo" }));
        } else {
          console.log("[]");
        }
      `,
    });

    const thread = await t3.thread({ project, title: "Fork feature", messages: ["Start"] });
    await t3.open(thread);
    const status = await runPromise(
      Effect.flatMap(rpcClient(T3_HOME, app.baseUrl ?? ""), (client) =>
        client["vcs.refreshStatus"]({ cwd: project }),
      ).pipe(Effect.scoped),
    );
    await screen.getByText("Start", { exact: true }).first().waitFor();
    await app.screenshot("thread-with-fork-merge-request");
    expect(status.pr?.url).toBe(mergeRequest.web_url);
    await screen.getByText("#42: Fork feature", { exact: true }).waitFor();
  },
);
