import { DatabaseSync } from "node:sqlite";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Held pin and settle shortcuts act once until released", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Shortcut demo");
  const one = await t3.thread({ project, title: "Thread Number 1", messages: ["Hello"] });
  const two = await t3.thread({ project, title: "Thread Number 2", messages: ["Hello"] });
  const three = await t3.thread({ project, title: "Thread Number 3", messages: ["Hello"] });
  const db = new DatabaseSync(`${T3_HOME}/userdata/statev2.sqlite`, { readOnly: true });
  const counts = (id: string) => db.prepare("SELECT event_type, count(*) AS count FROM orchestration_events WHERE stream_id = ? AND event_type IN ('thread.pinned','thread.unpinned','thread.settled','thread.unsettled') GROUP BY event_type ORDER BY event_type").all(id);
  const hold = async (key: string) => {
    await browser.keyboard.down("Control");
    await browser.keyboard.down("Shift");
    // Repeated down calls without keyup produce Chromium's native autoRepeat keydowns.
    for (let i = 0; i < 46; i++) {
      await browser.keyboard.down(key);
      await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 100)));
    }
    await browser.keyboard.up(key);
    await browser.keyboard.up("Shift");
    await browser.keyboard.up("Control");
  };
  try {
    await t3.open(one);
    await screen.getByTestId("composer-editor").tap();
    await browser.keyboard.press("Control+Shift+p");
    await screen.getByRole("button", "Unpin thread", { exact: true }).waitFor();
    const control = counts(one.threadId);
    await t3.open(two);
    await screen.getByTestId("composer-editor").tap();
    await hold("p");
    await app.screenshot("held-pin");
    const pin = counts(two.threadId);
    await t3.open(three);
    await screen.getByTestId("composer-editor").tap();
    await hold("s");
    await app.screenshot("held-settle");
    const settle = counts(three.threadId);
    const next = counts(two.threadId).filter(row => String(row.event_type).includes("settled"));
    console.log(JSON.stringify({ control, pin, settle, next }));
    expect({ control, pin, settle, next }).toEqual({
      control: [{ event_type: "thread.pinned", count: 1 }],
      pin: [{ event_type: "thread.pinned", count: 1 }],
      settle: [{ event_type: "thread.settled", count: 1 }],
      next: [],
    });
    await t3.open(two);
    await screen.getByTestId("composer-editor").tap();
    await browser.keyboard.press("Control+Shift+p");
    await expect.poll(() => counts(two.threadId)).toEqual([{ event_type: "thread.pinned", count: 1 }, { event_type: "thread.unpinned", count: 1 }]);
  } finally { db.close(); }
});
