import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { run } from "./shell.ts";
import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";
const decodePairing = Schema.decodeEffect(Schema.fromJsonString(Schema.Struct({ credential: Schema.String })));
const repository = { ".git/config": '[remote "origin"]\nurl = https://example.com/team/repo.git\n' };
test("Moving a branch with a same-named tag keeps topic for subsequent commits", WEB, async ({ t3, app, screen }) => {
  const source = await t3.project("Repository", repository);
  const git = (cwd: string, args: string[]) => runPromise(run("git", args, { cwd }));
  await git(source, ["checkout", "-b", "topic"]);
  await git(source, ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--allow-empty", "-m", "Topic work"]);
  await git(source, ["tag", "topic"]);
  const origin = app.baseUrl ?? "";
  const server = startSecondServer(origin);
  try {
    const { host } = await server.ready;
    const remote = makeState(SECOND_HOME);
    const second = await remote.state.project("Repository", repository);
    await git(second, ["fetch", "-u", source, "+main:main"]);
    await runPromise(Effect.gen(function* () {
      const primary = yield* rpcClient(T3_HOME, origin);
      const destination = yield* rpcClient(SECOND_HOME, host);
      for (const client of [primary, destination]) yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } });
      const pairing = yield* remote.cli(["auth", "pairing", "create", "--json"]);
      const { credential } = yield* decodePairing(pairing.stdout);
      yield* primary["peerLinks.link"]({ url: host, pairingCode: credential, access: "full-access" });
    }).pipe(Effect.scoped));
    const thread = await t3.thread({ project: source, title: "Topic work", messages: ["Start"] });
    await t3.open(thread);
    await screen.getByRole("button", "Thread actions for Topic work").tap();
    await screen.getByRole("menuitem", "Continue on another machine…").tap();
    await screen.getByRole("button", /^Move to /).tap();
    await screen.getByText(/^This thread continues on /).waitFor();
    const moved = await runPromise(Effect.gen(function* () {
      const destination = yield* rpcClient(SECOND_HOME, host);
      const item = yield* destination["orchestration.subscribeShell"]({}).pipe(Stream.runHead);
      if (item._tag !== "Some" || item.value.kind !== "snapshot") throw Error("No snapshot");
      const moved = item.value.snapshot.threads.find(({ title }) => title === "Topic work");
      if (!moved) throw Error("No moved thread");
      return moved;
    }).pipe(Effect.scoped));
    const target = await runPromise(environmentId(host));
    await app.open(`/${target}/${moved.id}`);
    await screen.getByRole("button", "Thread actions for Topic work").waitFor();
    await screen.getByRole("combobox", /^Branch:/).first().waitFor();
    await screen.getByText(/Syncing messages/).waitFor({ state: "hidden" });
    await app.screenshot("destination-branch");
    const worktree = moved.worktreePath ?? second;
    await git(worktree, ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--allow-empty", "-m", "Follow-up work"]);
    const actual = (await git(worktree, ["symbolic-ref", "HEAD"])).stdout.trim();
    expect(actual).toBe("refs/heads/topic");
    await expect(screen.getByRole("combobox", "Branch: topic", { exact: true }).first()).toBeVisible();
  } finally { await server.stop(); }
});
