import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";

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

test(
  "Going back from Pull Requests reveals the reopened thread in the sidebar",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const project = await t3.project("server");
    await t3.project("first-project");
    await runPromise(
      Effect.gen(function* () {
        const client = yield* rpcClient(T3_HOME, app.baseUrl);
        yield* client.subscribeServerConfig({}).pipe(
          Stream.filter((event) => {
            const providers =
              event.type === "snapshot"
                ? event.config.providers
                : event.type === "providerStatuses"
                  ? event.payload.providers
                  : [];
            return providers.some(
              (provider) =>
                provider.instanceId === "devReplay" &&
                provider.models.some((model) => model.slug === "multi-turn"),
            );
          }),
          Stream.runHead,
        );
      }).pipe(Effect.scoped, Effect.timeout("30 seconds")),
    );
    const thread = await t3.thread({
      project,
      title: "New thread",
      messages: ["Resume earlier work"],
    });
    await t3.open(thread);

    const threadRow = browser.locator(`[data-sidebar-row$=":${thread.threadId}"]`);
    await threadRow.waitFor({ timeout: 120_000 });
    await screen.getByRole("button", "Pull requests", { exact: true }).click();

    await screen.getByRole("combobox", "Projects", { exact: true }).click();
    await screen.getByRole("option", "first-project", { exact: true }).click();
    await screen.getByRole("combobox", "Projects: first-project").waitFor();
    await threadRow.waitFor({ state: "hidden" });

    await browser.back();
    await screen.getByText("Resume earlier work", { exact: true }).waitFor();
    await app.screenshot("thread-reopened-from-history");
    await expect(threadRow).toBeVisible();
  },
);
