import assert from "node:assert/strict";
import { test } from "bun:test";

import { __resetWebPerformanceTelemetryForTest, recordApiTiming, webPerformanceRouteTemplate, webPerformanceStatusClass } from "./rum";

test("web performance route templates remove high-cardinality identifiers", () => {
  assert.equal(webPerformanceRouteTemplate("/v1/agent/chat/result/trc_abc123456789"), "/v1/agent/chat/result/:id");
  assert.equal(webPerformanceRouteTemplate("/v1/workbench/workspace/cnv_abcdef/select-conversation"), "/v1/workbench/workspace/:id/select-conversation");
  assert.equal(webPerformanceRouteTemplate("/v1/hwpod-node-ops?traceId=trc_secret"), "/v1/hwpod-node-ops");
  assert.equal(webPerformanceRouteTemplate("#/workspace"), "/workspace");
});

test("web performance status class keeps API labels low-cardinality", () => {
  assert.equal(webPerformanceStatusClass(200), "2xx");
  assert.equal(webPerformanceStatusClass(404), "4xx");
  assert.equal(webPerformanceStatusClass(0), "network");
  assert.equal(webPerformanceStatusClass("bad"), "network");
  __resetWebPerformanceTelemetryForTest();
});

test("web performance telemetry does not record observability page API calls", () => {
  const previousWindow = globalThis.window;
  const previousDocument = globalThis.document;
  const previousPerformance = globalThis.performance;
  const previousFetch = globalThis.fetch;
  const events = [];
  globalThis.window = {
    location: { hash: "#/performance", origin: "http://web.test" },
    setTimeout: (handler: TimerHandler) => {
      if (typeof handler === "function") handler();
      return 0;
    },
    clearTimeout: () => undefined
  } as unknown as Window & typeof globalThis;
  globalThis.document = {} as Document;
  globalThis.performance = {} as Performance;
  globalThis.fetch = (async (_path: string, init?: RequestInit) => {
    events.push(JSON.parse(String(init?.body ?? "{}")));
    return new Response("{}", { status: 202, headers: { "content-type": "application/json" } });
  }) as typeof fetch;
  try {
    recordApiTiming({ path: "/v1/live-builds", durationMs: 1200, status: 200, outcome: "ok" });
    recordApiTiming({ path: "/v1/web-performance/summary", durationMs: 600, status: 200, outcome: "ok" });
    assert.equal(events.length, 0);
  } finally {
    globalThis.window = previousWindow;
    globalThis.document = previousDocument;
    globalThis.performance = previousPerformance;
    globalThis.fetch = previousFetch;
    __resetWebPerformanceTelemetryForTest();
  }
});
