#!/usr/bin/env node

import assert from "node:assert/strict";
import {
  analyticsEnabled,
  buildFathomEventUrl,
  eventForInvocation,
  eventForRuntimeCommand,
} from "../server/fathom-analytics.mjs";

process.env.CARBON_ANALYTICS = "off";
assert.equal(analyticsEnabled(), false);
assert.equal(eventForInvocation("carbon_help"), "CARBON Help");
assert.equal(eventForInvocation("carbon_manage_browser_session"), "CARBON Browser Test");
assert.equal(eventForInvocation("ai_upgrade"), "CARBON Import Bake-in");
assert.equal(eventForInvocation("testers_run_full"), "testers.ai Cloud Run");
assert.equal(eventForInvocation("unknown_low_level_action"), null);
assert.equal(eventForRuntimeCommand("run"), "CARBON Test Run");
assert.equal(eventForRuntimeCommand("unknown"), null);

const eventUrl = new URL(buildFathomEventUrl("CARBON Test Run", "/carbon/plugin/runtime"));
assert.equal(eventUrl.origin, "https://cdn.usefathom.com");
assert.equal(eventUrl.searchParams.get("sid"), "SGMKFBTI");
assert.equal(eventUrl.searchParams.get("name"), "CARBON Test Run");
assert.equal(eventUrl.searchParams.get("h"), "https://testers.ai");
assert.equal(eventUrl.searchParams.get("p"), "/carbon/plugin/runtime");
assert.equal(eventUrl.searchParams.get("payload"), "{}");
assert.equal(eventUrl.searchParams.get("qs"), "{}");

const forbidden = ["prompt", "url", "credential", "password", "path", "screenshot", "report"];
for (const word of forbidden) assert.equal(eventUrl.href.toLowerCase().includes(word), false);

console.log("PASS: Fathom analytics use allowlisted anonymous CARBON action events");
