import { spawn } from "node:child_process";
import { once } from "node:events";
import { join } from "node:path";
import { expect } from "e2e";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Product usage disclosures accurately say pseudonymous", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("disclosure-demo");
  await t3.open("/welcome");
  await screen.getByRole("link", "privacy policy").waitFor();
  await app.screenshot("welcome-disclosure");
  const welcome = await browser.evaluate<string>("document.body.innerText");
  await t3.open("/settings/about");
  await screen.getByRole("link", "View policy").waitFor();
  await app.screenshot("about-privacy-disclosure");
  const about = await browser.evaluate<string>("document.body.innerText");
  const marketing = join(APP_DIR, "apps/marketing");
  const server = spawn(process.execPath, [join(marketing, "node_modules/astro/bin/astro.mjs"), "dev", "--ignore-lock", "--host", "127.0.0.1", "--port", "14728"], { cwd: marketing, env: { ...process.env, ASTRO_TELEMETRY_DISABLED: "1" }, stdio: ["ignore", "pipe", "pipe"] });
  let privacy = "";
  try {
    await new Promise<void>((resolve, reject) => {
      server.once("error", reject);
      server.once("exit", (code) => reject(new Error(`Marketing exited: ${code}`)));
      server.stdout.on("data", (data) => { if (data.toString().includes("127.0.0.1:14728")) resolve(); });
      server.stderr.on("data", (data) => process.stderr.write(data));
    });
    await app.open("http://127.0.0.1:14728/privacy-policy");
    await screen.getByText("Product usage data.", { exact: true }).waitFor();
    await browser.evaluate(`(() => { const el = [...document.querySelectorAll("strong")].find(el => el.textContent === "Product usage data."); el.parentElement.scrollIntoView({ block: "center", behavior: "instant" }); return true; })()`);
    await browser.evaluate("(async () => { await document.fonts.ready; await Promise.all(document.getAnimations().map(a => a.finished.catch(() => {}))); return true; })()");
    await app.screenshot("marketing-product-usage-disclosure");
    privacy = await browser.evaluate<string>("document.body.innerText");
  } finally {
    if (server.exitCode === null) {
      const exited = once(server, "exit");
      server.kill("SIGTERM");
      await exited;
    }
  }
  expect(welcome).toContain("pseudonymous product usage data");
  expect(about).toContain("pseudonymous product usage data");
  expect(privacy).toContain("pseudonymous product usage data");
  expect(privacy).toContain("hashed random install ID");
  expect(privacy).toContain("hashed random IDs of the devices");
  expect(privacy).toContain("hashed account ID");
});
