/// <reference lib="dom" />
import * as Effect from "effect/Effect";
import { ProviderInstanceId } from "@t3tools/contracts";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Undo after answering preserves the draft history", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    const settings = yield* client["server.getSettings"]({});
    const instance = settings.providerInstances.devReplay!;
    yield* client["server.updateSettings"]({ patch: {}, providerInstanceMutation: {
      operation: "upsert", instanceId: ProviderInstanceId.make("devReplay"),
      instance: { ...instance, enabled: true, config: { ...instance.config, customModels: ["question"] } }
    } });
    yield* client["server.refreshProviders"]({ instanceId: ProviderInstanceId.make("devReplay"), cwd: project, fresh: true, refreshModels: true });
  }).pipe(Effect.scoped));
  const thread = await t3.thread({ project, title: "Question undo", messages: ["first"], model: "question" });
  await t3.open(thread);
  const answer = async () => {
    await browser.locator('[data-chat-composer-form="true"]').getByRole("button", "Strict schemas (Recommended) 1", { exact: true }).tap();
    await screen.getByRole("button", "Submit message", { exact: true }).waitFor();
  };
  await answer();
  const editor = browser.locator('[data-testid="composer-editor"]');
  await editor.tap();
  await browser.keyboard.type("Keep this");
  await browser.evaluate(() => {
    const clipboardData = new DataTransfer();
    clipboardData.setData("text/plain", " draft");
    document.activeElement!.dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }));
    return null;
  });
  await app.screenshot("draft-before-question");
  await runPromise(makeState(T3_HOME).cli(["thread", "send", thread.threadId, "again", "--wait", "--json"], [0, 2]));
  await answer();
  await editor.tap();
  await app.screenshot("draft-restored-after-answer");
  await browser.keyboard.press("Control+z");
  await app.screenshot("draft-after-one-undo");
  await expect.poll(() => editor.textContent()).toBe("Keep this");
});
