import {
  CustomFieldDef,
  CustomFieldEntityConfig
} from "@open-mercato/core/modules/entities/data/entities";
function buildVisibleScopeWhere(scope) {
  const organizationCandidates = [{ organizationId: null }];
  if (scope.organizationId) organizationCandidates.unshift({ organizationId: scope.organizationId });
  const tenantCandidates = [{ tenantId: null }];
  if (scope.tenantId) tenantCandidates.unshift({ tenantId: scope.tenantId });
  return {
    entityId: scope.entityId,
    $and: [
      { $or: organizationCandidates },
      { $or: tenantCandidates }
    ]
  };
}
function toMillis(value) {
  if (value instanceof Date) {
    const ms = value.getTime();
    return Number.isFinite(ms) ? ms : 0;
  }
  if (typeof value === "string" && value.length > 0) {
    const ms = Date.parse(value);
    return Number.isFinite(ms) ? ms : 0;
  }
  return 0;
}
async function latestUpdatedAtMillis(em, entity, where) {
  if (!entity) return 0;
  try {
    const row = await em.findOne(entity, where, {
      orderBy: { updatedAt: "desc" },
      fields: ["updatedAt"]
    });
    if (!row || typeof row !== "object") return 0;
    return toMillis(row.updatedAt);
  } catch {
    return 0;
  }
}
async function resolveEntityDefinitionsVersion(em, scope) {
  const where = buildVisibleScopeWhere(scope);
  const [defMillis, configMillis] = await Promise.all([
    latestUpdatedAtMillis(em, CustomFieldDef, where),
    latestUpdatedAtMillis(em, CustomFieldEntityConfig, where)
  ]);
  const newest = Math.max(defMillis, configMillis);
  if (!newest) return null;
  return new Date(newest).toISOString();
}
export {
  resolveEntityDefinitionsVersion
};
//# sourceMappingURL=definitions-version.js.map
