import { expect } from "e2e";
import { nativeRecorder } from "./native-proof-recording.ts";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";

import { MOBILE, MOBILE_T3_HOME as T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { run } from "./shell.ts";
import { makeState, rpcClient, runPromise } from "./t3.ts";
import { test, IOS } from "./t3-mobile.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", { ...IOS, video: "off" }, async ({ t3, app, screen, device }) => {
  const source = await t3.project("Source checkout", repository);
  const origin = `http://127.0.0.1:${MOBILE.serverPort}`;
  const server = startSecondServer(origin);
  let recording = false;
  const recorder = nativeRecorder();
  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();
    await screen.getByText("Ready to move", { exact: false }).first().waitFor({ timeout: 120_000 });
    await recorder.start("native-move");
    recording = true;
    await screen.getByText("Ready to move", { exact: false }).first().longPress();
    await screen.getByText("Continue on another machine", { exact: true }).tap();
    await screen.getByRole("button", /^Destination machine/).waitFor();
    await new Promise((resolve) => setTimeout(resolve, 1000));
    await screen.getByRole("button", /^Destination machine/).tap();
    await screen.getByText(/Several projects there have this repository/).waitFor();
    await app.screenshot("move-destination-project");
    await expect(screen.getByText("Choose a project", { exact: true })).toBeVisible();
    await expect(screen.getByText("First checkout", { exact: true })).toBeVisible();
    await screen.swipe({from:{x:201,y:800},to:{x:201,y:620},duration:500});
    await app.screenshot("available-checkouts");
    await screen.getByText("Second checkout", { exact: true }).tap();
    await screen.swipe({from:{x:201,y:800},to:{x:201,y:725},duration:500});
    await screen.swipe({from:{x:201,y:800},to:{x:201,y:540},duration:500});
    await app.screenshot("selected-checkout");
    await screen.getByRole("button", "Move", { exact: true }).tap();
    await screen.getByText("Ready to move", { exact: false }).first().waitFor();
    await screen.getByText("Ready to move", { exact: false }).first().tap();
    await screen.getByText("This thread continues on Destination machine", { exact: true }).waitFor({timeout: 60_000});
    await app.screenshot("move-completed");
    await screen.getByRole("button", "Open on Destination machine", {exact:true}).tap();
    await screen.getByText("Thread moved from", {exact:false}).waitFor();
    await app.screenshot("destination-conversation");
    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 {
    try {
      if (recording) await recorder.stop();
    } finally {
      try {
        await device.closeApp();
      } finally {
        await server.stop();
      }
    }
  }
});
