import { ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Stream from "effect/Stream";

import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test(
  "A right-panel terminal closed while viewing a file stays closed",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const project = await t3.project("demo", { "notes.txt": "Workspace notes" });
    const thread = await t3.thread({ project, title: "Shared terminals", messages: ["Start"] });
    const threadId = ThreadId.make(thread.threadId);
    await t3.open(thread);
    await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
    await screen.getByRole("button", "Terminal T", { exact: true }).tap();
    const input = browser
      .locator('[data-terminal-owner="right-panel"]')
      .getByRole("textbox", "Terminal input");
    await expect(input).toHaveAttribute("data-workspace-focus-default", "");

    await screen.getByRole("button", "Add panel surface").tap();
    await screen.getByRole("menuitem", /^Files/).tap();
    await screen.getByRole("treeitem", "notes.txt").tap();
    await input.waitFor({ state: "hidden" });

    const label = await runPromise(
      Effect.gen(function* () {
        const client = yield* rpcClient(T3_HOME, app.baseUrl);
        const terminal = yield* client.subscribeTerminalMetadata({}).pipe(
          Stream.flatMap((event) =>
            Stream.fromIterable(
              event.type === "snapshot"
                ? event.terminals
                : event.type === "upsert"
                  ? [event.terminal]
                  : [],
            ),
          ),
          Stream.filter((terminal) => terminal.threadId === threadId),
          Stream.runHead,
        );
        const { terminalId, label } = Option.getOrThrow(terminal);
        yield* client["terminal.close"]({ threadId, terminalId, deleteHistory: true });
        return label;
      }).pipe(Effect.scoped),
    );

    const terminalTab = screen.getByRole("button", label, { exact: true });
    if (await terminalTab.isVisible()) await terminalTab.tap();
    try {
      await expect(terminalTab).toBeHidden();
    } finally {
      await app.screenshot("after-returning-to-the-closed-terminal");
    }
  },
);
