import assert from "node:assert/strict";
import { GELIOS_CAPABILITIES } from "../capabilities.mjs";
import { readConfig, unitIsInScope } from "../config.mjs";
import { toFleetPositionPatch, toFleetPositionsSnapshot } from "../data-products.mjs";
import { extractUnitItems, normalizeUnit } from "../normalize.mjs";

const unit = normalizeUnit({
  id: 42,
  name: "Sample fleet fixture",
  lmsg: { time: 1_789_123_456, lat: 55.75, lon: 37.61, speed: 12.5, gps_valid: true, sats: 11 },
}, { tenantId: "sample-tenant", connectionId: "gelios-sample", receivedAt: new Date("2026-07-13T00:00:00.000Z") });
assert.equal(unit.stableSubjectId, "gelios.unit:gelios-sample:42");
assert.equal(unit.latitude, 55.75);
assert.equal(unit.longitude, 37.61);
assert.equal(unit.gpsValid, true);
assert.equal(extractUnitItems({ items: [{ id: 1 }] }).length, 1);
assert.equal(extractUnitItems({ units: [{ id: 1 }] }).length, 1);
assert.equal(GELIOS_CAPABILITIES.some((item) => item.enabled === true && item.class.includes("write")), false);
assert.equal(GELIOS_CAPABILITIES.some((item) => item.id === "gelios.commands.send" && item.enabled === false), true);
const snapshot = toFleetPositionsSnapshot([unit], {
  tenantId: "sample-tenant",
  connectionId: "gelios-sample",
  generatedAt: new Date("2027-09-01T00:00:00.000Z"),
  staleAfterMs: 300_000,
});
assert.equal(snapshot.dataProduct.id, "fleet.positions.current.v1");
assert.equal(snapshot.entities[0].semanticType, "map.moving_object");
assert.equal(snapshot.entities[0].status, "stale");
assert.equal(Object.hasOwn(snapshot.entities[0], "telemetry"), false);
assert.equal(toFleetPositionPatch({ ...unit, latitude: null, longitude: null }, {
  generatedAt: new Date("2026-07-13T00:00:00.000Z"),
  staleAfterMs: 300_000,
}).entity.status, "no-position");

const configBase = {
  DATABASE_URL: "postgresql://fixture",
  GELIOS_TENANT_ID: "fixture-tenant",
  GELIOS_CONNECTION_ID: "fixture-connection",
  GELIOS_INTAKE_ENABLED: "true",
};
const allUnitsConfig = readConfig({ ...configBase, GELIOS_UNIT_SCOPE: "all" });
assert.equal(allUnitsConfig.unitScope, "all");
assert.equal(unitIsInScope(allUnitsConfig, 1), true);
assert.equal(unitIsInScope(allUnitsConfig, 99_999), true);
const allowlistConfig = readConfig({ ...configBase, GELIOS_UNIT_SCOPE: "allowlist", GELIOS_ALLOWED_UNIT_IDS: "7,11" });
assert.equal(unitIsInScope(allowlistConfig, 7), true);
assert.equal(unitIsInScope(allowlistConfig, 8), false);
assert.throws(() => readConfig({ ...configBase, GELIOS_UNIT_SCOPE: "everything" }), /GELIOS_UNIT_SCOPE/);

console.log(JSON.stringify({
  ok: true,
  checks: [
    "unit_normalization",
    "safe_intake_registry",
    "provider_neutral_data_product",
    "all_units_connection_scope",
    "command_transport_absent",
  ],
}));
