import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("entities").child({ component: "definitions-cache" });
const CACHE_PREFIX = "entities:definitions";
const ENTITY_DEFINITIONS_CACHE_TTL_MS = 5 * 60 * 1e3;
function normalizeTenantId(tenantId) {
  return tenantId ?? "global";
}
function normalizeOrganizationId(organizationId) {
  return organizationId ?? "none";
}
function createDefinitionsCacheKey(options) {
  const tenant = normalizeTenantId(options.tenantId);
  const organization = normalizeOrganizationId(options.organizationId);
  const scope = options.entityIds.join("|");
  return `${CACHE_PREFIX}:${tenant}:${organization}:entities=${scope}`;
}
function createDefinitionsCacheTags(options) {
  const tenant = normalizeTenantId(options.tenantId);
  const organization = normalizeOrganizationId(options.organizationId);
  const baseTenant = `${CACHE_PREFIX}:${tenant}`;
  const tags = /* @__PURE__ */ new Set([
    baseTenant,
    `${baseTenant}:org:${organization}`
  ]);
  const uniqueEntities = Array.from(new Set(options.entityIds));
  for (const entityId of uniqueEntities) {
    tags.add(`${baseTenant}:entity:${entityId}`);
    tags.add(`${baseTenant}:org:${organization}:entity:${entityId}`);
  }
  return Array.from(tags);
}
async function invalidateDefinitionsCache(cache, options) {
  if (!cache?.deleteByTags) return;
  const tags = createDefinitionsCacheTags(options);
  const entityTags = tags.filter((tag) => tag.includes(":entity:"));
  const targets = entityTags.length ? entityTags : tags;
  if (!targets.length) return;
  try {
    await cache.deleteByTags(targets);
  } catch (err) {
    logger.warn("Failed to invalidate cache", { err });
  }
}
export {
  ENTITY_DEFINITIONS_CACHE_TTL_MS,
  createDefinitionsCacheKey,
  createDefinitionsCacheTags,
  invalidateDefinitionsCache
};
//# sourceMappingURL=definitions.cache.js.map
