import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
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 { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const decodePairing = Schema.decodeEffect(
  Schema.fromJsonString(Schema.Struct({ credential: Schema.String })),
);

test("A moved thread outside git brings its files", WEB, async ({ t3, app, screen }) => {
  // Outside any repository, like a scratch task folder.
  const source = await runPromise(
    Effect.gen(function* () {
      const fs = yield* FileSystem.FileSystem;
      const path = yield* Path.Path;
      const parent = yield* fs.makeTempDirectory({ prefix: "t3-scratch-" });
      const folder = path.join(parent, "Scratch task");
      yield* fs.makeDirectory(folder);
      yield* fs.writeFileString(path.join(folder, "notes.md"), "work in progress\n");
      yield* makeState(T3_HOME).cli(["project", "add", folder]);
      return folder;
    }),
  );
  const origin = app.baseUrl ?? "";
  const server = startSecondServer(origin);
  try {
    const { host } = await server.ready;
    const remote = makeState(SECOND_HOME);
    const destinationRoot = await remote.state.project("Scratch there");
    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: "Scratch move", messages: ["Start"] });
    await t3.open(thread);
    await screen.getByRole("button", "Thread actions for Scratch move").tap();
    await screen.getByRole("menuitem", "Continue on another machine…").tap();
    await screen.getByText(/Choose the destination project/).waitFor();
    await app.screenshot("move-dialog-promises-code");
    await screen.getByRole("button", "Cancel").tap();
    // The dialog's picker lists the destination's projects only when this client syncs them;
    // start the same move with the project the user would pick there.
    await runPromise(
      Effect.gen(function* () {
        const primary = yield* rpcClient(T3_HOME, origin);
        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 there = item.value.snapshot.projects.find(({ title }) => title === "Scratch there");
        const options = yield* primary["threadHandoff.options"]({ threadId: thread.threadId });
        const target = options.options[0];
        if (there === undefined || target === undefined) throw Error("No destination");
        yield* primary["threadHandoff.start"]({
          threadId: thread.threadId,
          environmentId: target.environmentId,
          projectId: there.id,
        });
      }).pipe(Effect.scoped),
    );
    await screen.getByText(/^This thread continues on /).waitFor();
    await app.screenshot("move-done");
    const cwd = 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 === "Scratch move");
        if (moved === undefined) throw Error("The thread did not arrive");
        return (
          moved.worktreePath ??
          projects.find(({ id }) => id === moved.projectId)?.workspaceRoot ??
          destinationRoot
        );
      }).pipe(Effect.scoped),
    );
    const arrived = await runPromise(
      Effect.gen(function* () {
        const fs = yield* FileSystem.FileSystem;
        const path = yield* Path.Path;
        return yield* fs.exists(path.join(cwd, "notes.md"));
      }),
    );
    expect(arrived).toBe(true);
  } finally {
    await server.stop();
  }
});
