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 { 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("A move can choose between projects on a linked machine", { ...WEB, video: "off" }, async ({ t3, app, screen, browser }) => {
  const source = await t3.project("Source checkout", repository);
  const origin = app.baseUrl ?? "";
  const server = startSecondServer(origin);
  let recording = false;
  try {
    const { host } = await server.ready;
    const remote = makeState(SECOND_HOME);
    await remote.state.project("First checkout", repository);
    const second = await remote.state.project("Second checkout", repository);
    await runPromise(
      Effect.gen(function* () {
        yield* run("git", ["fetch", "-u", source, "+main:main"], { cwd: second });
        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: "approval-required",
        });
      }).pipe(Effect.scoped),
    );

    const thread = await t3.thread({
      project: source,
      title: "Ready to move",
      messages: ["Start"],
    });
    await t3.open(thread);
    await screen.getByRole("button", "Thread actions for Ready to move").waitFor();
    await app.startRecording({ name: "move-thread" });
    recording = true;
    await screen.getByRole("button", "Thread actions for Ready to move").tap();
    await screen.getByRole("menuitem", "Continue on another machine…").tap();
    await screen.getByText(/Several projects there have this repository/).waitFor();
    await browser.evaluate(() => new Promise<void>((resolve) => setTimeout(resolve, 1000)));
    await app.screenshot("move-destination-project");
    await expect(screen.getByRole("combobox", "Choose a project")).toBeVisible();
    await screen.getByRole("combobox", "Choose a project").tap();
    await expect(screen.getByRole("option", /^First checkout/)).toBeVisible();
    await browser.evaluate(() => new Promise<void>((resolve) => setTimeout(resolve, 1000)));
    await app.screenshot("available-checkouts");
    await screen.getByRole("option", /^Second checkout/).tap();
    await browser.evaluate(() => new Promise<void>((resolve) => setTimeout(resolve, 1000)));
    await app.screenshot("selected-checkout");
    await screen.getByRole("button", /^Move to /).tap();
    await screen.getByText(/^This thread continues on /).waitFor();
    await screen.getByText("Thread moved from", { exact: false }).waitFor();
    await browser.evaluate(() => new Promise<void>((resolve) => setTimeout(resolve, 1000)));
    await app.screenshot("destination-conversation");
    await browser.evaluate(() => new Promise<void>((resolve) => setTimeout(resolve, 2000)));
    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 { projects, threads } = item.value.snapshot;
        const moved = threads.find(({ title }) => title === "Ready to move");
        expect(projects.find(({ id }) => id === moved?.projectId)?.workspaceRoot).toBe(second);
      }).pipe(Effect.scoped),
    );
  } finally {
    if (recording) await app.stopRecording();
    await t3.open("/settings/general");
    await server.stop();
  }
});
