import assert from "node:assert/strict";
import test from "node:test";
import { DefaultProxy, Resource } from "cesium";

const gatewayProxyBase = "/api/map-gateway/api/map/cache?url=";

function decodedGatewayTarget(resource) {
  const browserUrl = new URL(resource.url, "https://foundry.nodedc.test");
  assert.equal(browserUrl.pathname, "/api/map-gateway/api/map/cache");
  const target = browserUrl.searchParams.get("url");
  assert.ok(target);
  return new URL(target);
}

test("OSM Buildings external JSON and b3dm inherit the Gateway cache route", () => {
  const root = new Resource({
    url: "https://assets.ion.cesium.com/asset_depot/96188/OpenStreetMap/tileset.json?v=19&nodedc_client_revision=2",
    proxy: new DefaultProxy(gatewayProxyBase),
  });
  const externalTileset = root.getDerivedResource({ url: "0-0-0.json" });
  const buildingTile = externalTileset.getDerivedResource({ url: "14/31780/12975.b3dm" });

  const externalTarget = decodedGatewayTarget(externalTileset);
  const buildingTarget = decodedGatewayTarget(buildingTile);
  assert.equal(externalTarget.pathname, "/asset_depot/96188/OpenStreetMap/0-0-0.json");
  assert.equal(buildingTarget.pathname, "/asset_depot/96188/OpenStreetMap/14/31780/12975.b3dm");
  for (const target of [externalTarget, buildingTarget]) {
    assert.equal(target.searchParams.get("v"), "19");
    assert.equal(target.searchParams.get("nodedc_client_revision"), "2");
    assert.equal(target.searchParams.has("access_token"), false);
  }
});

test("append-only and passthrough cache intent is inherited by Buildings children", () => {
  for (const cacheQuery of [
    "nodedc_client_revision=2",
    "nodedc_client_revision=2&nodedc_cache_mode=passthrough",
    "nodedc_client_revision=2&nodedc_cache_refresh=1",
  ]) {
    const root = new Resource({
      url: `https://assets.ion.cesium.com/96188/tileset.json?${cacheQuery}`,
      proxy: new DefaultProxy(gatewayProxyBase),
    });
    const target = decodedGatewayTarget(root.getDerivedResource({ url: "root.b3dm" }));
    for (const [name, value] of new URLSearchParams(cacheQuery)) {
      assert.equal(target.searchParams.get(name), value);
    }
  }
});
