import { geliosProviderPackageV11 } from "../v11/package.mjs";

export const GELIOS_PROVIDER_PACKAGE_ID = "gelios.provider.v12";
export const GELIOS_PROVIDER_PACKAGE_VERSION = "12.0.1";
export const GELIOS_UNIT_IDENTITY_DATA_PRODUCT_ID = "fleet.units.identity.current.v1";
export const GELIOS_UNIT_IDENTITY_DATA_PRODUCT_VERSION = "1.0.0";
export const GELIOS_UNIT_IDENTITY_ONTOLOGY_REVISION = "ontology.map.moving_object.v3";

const IDENTITY_CONTRACT_VERSION = "12.0.0";
const IDENTITY_CAPABILITY_ID = "gelios.units.identity.read";
const UNITS_CAPABILITY_ID = "gelios.units.current.read";
const IDENTITY_PROFILE_ID = "gelios.units.identity.warm.v1";
const IDENTITY_MAPPING_ID = "gelios.units.to.fleet.units.identity.current.v1";
const IDENTITY_TEMPLATE_ID = "gelios.units.identity.l2.v1";

const value = structuredClone(geliosProviderPackageV11);
value.id = GELIOS_PROVIDER_PACKAGE_ID;
value.version = GELIOS_PROVIDER_PACKAGE_VERSION;
value.manifest = {
  ...value.manifest,
  id: "gelios.provider.manifest.v12",
  version: GELIOS_PROVIDER_PACKAGE_VERSION,
};

const identityCapability = value.capabilities.find(
  (capability) => capability.id === IDENTITY_CAPABILITY_ID,
);
if (!identityCapability) throw new Error("gelios_v12_identity_capability_missing");
prependItemsCollectionPath(identityCapability);

const unitsCapability = value.capabilities.find(
  (capability) => capability.id === UNITS_CAPABILITY_ID,
);
if (!unitsCapability) throw new Error("gelios_v12_units_capability_missing");
prependItemsCollectionPath(unitsCapability);

const identityProfile = value.collectionProfiles.find(
  (profile) => profile.id === IDENTITY_PROFILE_ID,
);
if (!identityProfile) throw new Error("gelios_v12_identity_profile_missing");
identityProfile.version = IDENTITY_CONTRACT_VERSION;

const identityMapping = value.mappingContracts.find(
  (mapping) => mapping.id === IDENTITY_MAPPING_ID,
);
if (!identityMapping) throw new Error("gelios_v12_identity_mapping_missing");
identityMapping.version = IDENTITY_CONTRACT_VERSION;

const identityTemplate = value.l2Templates.find(
  (template) => template.id === IDENTITY_TEMPLATE_ID,
);
if (!identityTemplate) throw new Error("gelios_v12_identity_template_missing");
identityTemplate.version = IDENTITY_CONTRACT_VERSION;

export const geliosProviderPackageV12 = deepFreeze(value);

function prependItemsCollectionPath(capability) {
  capability.request.response.collectionPaths = [
    "items",
    ...capability.request.response.collectionPaths.filter(
      (path) => path !== "items",
    ),
  ];
}

function deepFreeze(input) {
  if (!input || typeof input !== "object" || Object.isFrozen(input)) return input;
  Object.freeze(input);
  for (const child of Object.values(input)) deepFreeze(child);
  return input;
}
