import assert from "node:assert/strict";
import { test } from "bun:test";
import { monitorRouteHref, readMonitorRoute, withMonitorRoute } from "../assets/web-probe-sentinel-monitor-workbench/state/monitor-route.js";

Object.assign(globalThis, { window: { location: { origin: "https://monitor.example.test" } } });

test("monitor route roundtrips run detail tab and filters", () => {
  const route = readMonitorRoute("https://monitor.example.test/monitor/runs/run-1/findings/finding-2?sentinelId=s1&node=NC01&lane=v03&status=failed&tab=findings");
  assert.equal(route.kind, "detail");
  assert.equal(route.detailType, "finding");
  assert.equal(monitorRouteHref(route), "/monitor/runs/run-1/findings/finding-2?sentinelId=s1&node=NC01&lane=v03&status=failed&tab=findings");
});

test("monitor route rejects unsupported paths and filter changes clear selection", () => {
  assert.deepEqual(readMonitorRoute("https://monitor.example.test/dashboard"), { kind: "invalid", reason: "unsupported_path" });
  const next = withMonitorRoute(readMonitorRoute("https://monitor.example.test/monitor/runs/run-1"), { kind: "workspace", runId: "", filters: { status: "failed" } });
  assert.equal(monitorRouteHref(next), "/monitor?status=failed");
});

test("monitor route rejects invalid tab status time range and malformed encoding", () => {
  assert.equal(readMonitorRoute("https://monitor.example.test/monitor?tab=raw").reason, "invalid_tab");
  assert.equal(readMonitorRoute("https://monitor.example.test/monitor?status=surprise").reason, "invalid_status");
  assert.equal(readMonitorRoute("https://monitor.example.test/monitor?from=invalid").reason, "invalid_time_range");
  assert.equal(readMonitorRoute("https://monitor.example.test/monitor?from=2026-07-13T05:00:00Z&to=2026-07-13T04:00:00Z").reason, "invalid_time_range");
  assert.equal(readMonitorRoute("https://monitor.example.test/monitor/runs/%E0%A4%A").reason, "malformed_url_encoding");
});

test("monitor route roundtrips diagnostic detail", () => {
  const route = readMonitorRoute("https://monitor.example.test/monitor/runs/run-1/diagnostics/runtime?sentinelId=s1&node=NC01&lane=v03&tab=diagnostics");
  assert.equal(route.detailType, "diagnostic");
  assert.equal(route.detailId, "runtime");
  assert.equal(monitorRouteHref(route), "/monitor/runs/run-1/diagnostics/runtime?sentinelId=s1&node=NC01&lane=v03&tab=diagnostics");
});
