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

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

test(
  "Committing on a new branch keeps the starting branch as its base",
  WEB,
  async ({ t3, app, screen }) => {
    const project = await t3.project("demo");
    const git = (...args: string[]) => runPromise(run("git", args, { cwd: project }));
    await git("config", "user.name", "Scenario");
    await git("config", "user.email", "scenario@example.invalid");
    await git("switch", "-c", "terminal-work");
    await git("commit", "--allow-empty", "-m", "Unrelated branch commit");
    await git("switch", "main");

    const input = { project, title: "Commit work", messages: ["Start"] };
    const thread = await t3.thread({ ...input, model: "default" }).catch((error: unknown) => {
      if (!String(error).includes("Model default is not advertised by provider devReplay.")) {
        throw error;
      }
      return t3.thread(input);
    });
    await runPromise(
      Effect.flatMap(FileSystem.FileSystem, (fs) =>
        fs.writeFileString(`${project}/README.md`, "A local edit\n"),
      ),
    );
    await t3.open(thread);
    await screen.getByRole("button", "Git action options").tap();
    await screen.getByRole("menuitem", "Commit", { exact: true }).tap();
    await screen.getByPlaceholder("Leave empty to auto-generate").fill("Add local notes");

    const shim = writeFakeCli({
      directory: `${T3_HOME}/bin`,
      name: "git",
      source: `
        import { spawnSync } from "node:child_process";
        import { dirname, delimiter } from "node:path";
        import { fileURLToPath } from "node:url";
        process.env.PATH = process.env.PATH.split(delimiter)
          .filter((entry) => entry !== dirname(fileURLToPath(import.meta.url))).join(delimiter);
        const args = process.argv.slice(2);
        // Switch in another Git process after the action starts and before it creates the branch.
        if (process.cwd() === ${JSON.stringify(project)} &&
            args.join(" ") === "branch --list --no-column --format=%(refname:lstrip=2)") {
          const switched = spawnSync("git", ["switch", "--quiet", "terminal-work"], { stdio: "inherit" });
          if (switched.status !== 0) process.exit(switched.status ?? 1);
        }
        const result = spawnSync("git", args, { stdio: "inherit" });
        process.exit(result.status ?? 1);
      `,
    });
    try {
      await screen.getByRole("button", "Commit on new branch", { exact: true }).tap();
      const success = screen.getByText(/^Committed [0-9a-f]+$/);
      const failure = screen.getByText("Action failed", { exact: true });
      await success.or(failure).first().waitFor();

      const unexpectedBase =
        (await success.isVisible()) &&
        (await git("log", "-1", "--format=%s", "HEAD^")).stdout.trim() ===
          "Unrelated branch commit";
      await app.screenshot("feature-commit-after-switch");
      expect(unexpectedBase).toBe(false);
      // The injected switch must have landed and stopped the action before any branch was made.
      await screen.getByText(/main is no longer checked out/).waitFor();
      expect((await git("branch", "--show-current")).stdout.trim()).toBe("terminal-work");
      expect((await git("branch", "--list", "feature/*")).stdout.trim()).toBe("");
    } finally {
      await runPromise(Effect.flatMap(FileSystem.FileSystem, (fs) => fs.remove(shim)));
    }
  },
);
