import { readFile } from "node:fs/promises";
import { T3_HOME } from "../e2e.config.ts";
import { expect } from "e2e";
import { chromium } from "playwright-core";
import { test, WEB } from "./t3.ts";

test("An externally archived thread appears in the open Archive", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Archive demo");
  await t3.thread({ project, title: "Release checklist", messages: ["Prepare the checklist"] });
  await t3.open();
  await screen.getByText("Release checklist", { exact: true }).first().waitFor({ state: "visible" });
  await app.open("/settings/archived");
  await screen.getByText("No archived threads", { exact: true }).waitFor({ state: "visible" });
  const stableCapture = async (label: string) => {
    let previous = await app.screenshot(`${label}-settling`);
    for (let attempt = 0; attempt < 6; attempt++) {
      await new Promise((resolve) => setTimeout(resolve, 500));
      const current = await app.screenshot(label);
      if ((await readFile(previous)).equals(await readFile(current))) return;
      previous = current;
    }
    throw new Error("The Archive capture did not settle");
  };
  await stableCapture("archive-before-external-action");
  const external = await chromium.launch({ headless: true });
  try {
    const context = await external.newContext({ viewport: { width: 1280, height: 800 }, recordVideo: { dir: process.env.PROOF_RECORDINGS!, size: { width: 1280, height: 800 } } });
    await context.addCookies(await browser.cookies());
    const second = await context.newPage();
    await second.goto(new URL(await readFile(`${T3_HOME}/pairing-path`, "utf8"), await browser.url()).href);
    const row = second.locator("[data-thread-item]").filter({ hasText: "Release checklist" });
    await row.click({ button: "right" });
    await second.getByText("Archive thread", { exact: true }).click();
    await row.waitFor({ state: "hidden" });
    // Keep the first client mounted: the shell event must refresh its cached Archive.
    try {
      await expect(screen.getByRole("button", "Unarchive Release checklist")).toBeVisible();
    } finally {
      await stableCapture("archive-after-external-action");
    }
  } finally {
    await external.close();
  }
});
