/// <reference lib="dom" />
import { CommandId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";

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

test(
  "Undo returns an older pin to its place in the sidebar",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const project = await t3.project("demo");
    const startThread = (title: string) => {
      const input = { project, title, messages: ["Start"] };
      return t3.thread({ ...input, model: "default" }).catch((error: unknown) => {
        if (!String(error).includes("Model default is not advertised by provider devReplay.")) {
          throw error;
        }
        return t3.thread(input);
      });
    };
    const older = await startThread("Older pin");
    const arranged = await startThread("Arranged pin");

    await runPromise(
      Effect.gen(function* () {
        const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
        // Older versions saved pins without a manual order key.
        yield* client["orchestration.dispatchCommand"]({
          type: "thread.pin",
          commandId: CommandId.make(`scenario:pin:${older.threadId}`),
          threadId: ThreadId.make(older.threadId),
        });
        yield* client["orchestration.dispatchCommand"]({
          type: "thread.pin",
          commandId: CommandId.make(`scenario:pin:${arranged.threadId}`),
          threadId: ThreadId.make(arranged.threadId),
          orderKey: "m",
        });
      }).pipe(Effect.scoped),
    );

    await t3.open(arranged);
    const olderRow = browser.locator(`li[data-thread-item$=":${older.threadId}"]`);
    const unpin = olderRow.getByRole("button", "Unpin thread", { exact: true });
    await unpin.tap();
    await unpin.waitFor({ state: "detached" });
    await screen.getByRole("button", /undo/i).tap();
    await unpin.waitFor();
    // Reload so the order comes from the server, not the optimistic restore.
    await t3.open(arranged);
    await unpin.waitFor();

    await app.screenshot("pinned-order-after-undo");
    const pinnedOrder = await browser.evaluate(
      (pins) =>
        [...document.querySelectorAll("li[data-thread-item]")]
          .filter((row) => row.querySelector('button[aria-label="Unpin thread"]'))
          .flatMap((row) =>
            pins.flatMap(({ id, title }) =>
              row.getAttribute("data-thread-item")?.endsWith(`:${id}`) ? [title] : [],
            ),
          ),
      [
        { id: older.threadId, title: "Older pin" },
        { id: arranged.threadId, title: "Arranged pin" },
      ],
    );
    expect(pinnedOrder).toEqual(["Arranged pin", "Older pin"]);
  },
);
