import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { runPromise, test, WEB } from "./t3.ts";

test("Project actions read externally rewritten t3.json when reopened", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Port demo", {
    "t3.json": JSON.stringify({ scripts: [{ name: "Dev", command: "npm run dev -- --port 4100" }] }),
  });
  const thread = await t3.thread({ project, title: "Project actions refresh", messages: ["Start"] });
  await browser.setViewport({ width: 1440, height: 1000 });
  await t3.open(thread);
  const actions = screen.getByRole("button", "Choose project action", { exact: true });
  await actions.tap();
  await screen.getByRole("menuitem", /^Dev Import$/).waitFor();
  await app.screenshot("initial-actions");
  await browser.keyboard.press("Escape");
  await runPromise(Effect.flatMap(FileSystem.FileSystem, (fs) => fs.writeFileString(`${project}/t3.json`, JSON.stringify({ scripts: [
    { name: "Dev 4200", command: "npm run dev -- --port 4200" },
    { name: "Test 4201", command: "npm test -- --port 4201" },
  ] }))));
  // Match the reported delay beyond the query's former 30-second stale window.
  await new Promise((resolve) => setTimeout(resolve, 60000));
  await actions.tap();
  await app.screenshot("reopened-actions-after-disk-edit");
  await expect(screen.getByRole("menuitem", /^Dev 4200 Import$/)).toBeVisible();
  await expect(screen.getByRole("menuitem", /^Test 4201 Import$/)).toBeVisible();
});
