import { readFileSync } from "node:fs";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Provider failure withdraws an unanswerable approval", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("approval-demo", { "README.md": "Synthetic approval failure demonstration.\n" });
  await t3.open();
  await screen.getByRole("textbox").waitFor({ state: "visible" });
  await browser.evaluate(async () => {
    await (window as any).t3dev.replay("approval");
  });
  await screen.getByRole("button", "Approve", { exact: true }).waitFor({ state: "visible" });
  await app.screenshot("approval-before-provider-failure");
  const records = readFileSync(process.env.PROOF_PID_LOG!, "utf8").trim().split("\n").map(line => JSON.parse(line));
  const spawned = records.at(-1);
  if (!spawned?.pid) throw new Error("No replay provider PID captured at spawn");
  process.kill(spawned.pid, "SIGKILL");
  await screen.getByText("Provider error", { exact: false }).first().waitFor({ state: "visible" });
  await app.screenshot("approval-after-provider-failure");
  await expect(screen.getByRole("button", "Approve", { exact: true })).toBeHidden();
  await expect(screen.getByText("Waiting for approval", { exact: true })).toBeHidden();
});
