import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./issue-40174-server.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("The @ menu offers a machine linked only through the thread server", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("demo", { "build-notes.md": "Synthetic build notes" });
  const thread = await t3.thread({ project, title: "Build work", messages: ["first"] });
  const server = startSecondServer(app.baseUrl ?? "");
  try {
    const { host } = await server.ready;
    await runPromise(Effect.gen(function* () {
      const primary = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      const second = yield* rpcClient(SECOND_HOME, host);
      for (const client of [primary, second]) {
        yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } });
      }
      const paired = yield* makeState(SECOND_HOME).cli(["auth", "pairing", "create", "--json"]);
      const { credential } = JSON.parse(paired.stdout);
      yield* primary["peerLinks.link"]({ url: host, pairingCode: credential, access: "read-only" });
    }).pipe(Effect.scoped));
    await t3.open("/settings/connections");
    await screen.getByText("buildbox", { exact: true }).first().waitFor();
    await app.screenshot("server-link-control");
    await t3.open(thread);
    await screen.getByRole("textbox").fill("@build");
    try {
      await expect(screen.getByRole("option", /buildbox/)).toBeVisible();
    } finally {
      await app.screenshot("machine-mention");
    }
  } finally {
    await server.stop();
  }
});
