import { createLogger } from "../logger/index.js";
const logger = createLogger("shared").child({ component: "encryption" });
let _entityIds = null;
let _entityIdLookup = null;
function registerEntityIds(E) {
  if (_entityIds !== null && process.env.NODE_ENV === "development") {
    logger.debug("Entity IDs re-registered (this may occur during HMR)");
  }
  _entityIds = E;
  _entityIdLookup = null;
}
function getEntityIds(throwIfNotRegistered = true) {
  if (!_entityIds) {
    if (throwIfNotRegistered) {
      throw new Error("[Bootstrap] Entity IDs not registered. Call registerEntityIds() at bootstrap.");
    }
    return {};
  }
  return _entityIds;
}
const toSnake = (value) => value.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[\s-]+/g, "_").replace(/__+/g, "_").toLowerCase();
function getEntityIdLookup() {
  if (_entityIdLookup) return _entityIdLookup;
  const E = getEntityIds();
  const map = /* @__PURE__ */ new Map();
  for (const mod of Object.values(E || {})) {
    for (const [key, entityId] of Object.entries(mod || {})) {
      const snake = toSnake(key);
      map.set(snake, entityId);
      map.set(key.toLowerCase(), entityId);
      map.set(
        key.split("_").map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(""),
        entityId
      );
    }
  }
  _entityIdLookup = map;
  return map;
}
const normalizeKey = (value) => value.replace(/["'`]/g, "").replace(/[\W]+/g, "_").replace(/__+/g, "_").toLowerCase();
const maybeSingularize = (value) => {
  if (value.endsWith("ies")) return `${value.slice(0, -3)}y`;
  if (value.endsWith("s")) return value.slice(0, -1);
  return value;
};
function resolveEntityIdFromMetadata(meta) {
  if (!meta) return null;
  const candidates = [
    meta.className,
    meta.name,
    meta.collection,
    meta.tableName
  ].filter(Boolean);
  for (const raw of candidates) {
    const normalized = normalizeKey(raw);
    const singular = maybeSingularize(normalized);
    const snake = toSnake(raw);
    const snakeSingular = maybeSingularize(snake);
    const variants = [
      normalized,
      singular,
      normalized.replace(/_/g, ""),
      // Pascal-ish fallback
      singular.replace(/_/g, ""),
      snake,
      snakeSingular
    ];
    const lookup = getEntityIdLookup();
    for (const candidate of variants) {
      if (!candidate) continue;
      const id = lookup.get(candidate);
      if (id) return id;
    }
  }
  return null;
}
export {
  getEntityIds,
  registerEntityIds,
  resolveEntityIdFromMetadata
};
//# sourceMappingURL=entityIds.js.map
