import { decryptCustomFieldValue } from "./customFieldValues.js";
async function decryptValue(value, scope, service, cache) {
  if (Array.isArray(value)) {
    return Promise.all(value.map((entry) => decryptCustomFieldValue(entry, scope.tenantId, service, cache)));
  }
  return decryptCustomFieldValue(value, scope.tenantId, service, cache);
}
async function decryptIndexDocCustomFields(doc, scope, service, cache) {
  const keys = Object.keys(doc).filter((key) => key.startsWith("cf:") || key.startsWith("cf_"));
  if (!keys.length) return doc;
  const working = { ...doc };
  await Promise.all(
    keys.map(async (key) => {
      try {
        working[key] = await decryptValue(working[key], scope, service, cache);
      } catch {
      }
    })
  );
  return working;
}
async function decryptIndexDocForSearch(entityId, doc, scope, service, cache) {
  if (!service || typeof service.decryptEntityPayload !== "function") {
    return decryptIndexDocCustomFields(doc, scope, service, cache);
  }
  if (service.isEnabled?.() === false) {
    return decryptIndexDocCustomFields(doc, scope, service, cache);
  }
  let working = doc;
  const decryptEntity = async (targetEntityId) => {
    const decrypted = await service.decryptEntityPayload(
      targetEntityId,
      working,
      scope.tenantId ?? null,
      scope.organizationId ?? null
    );
    working = { ...working, ...decrypted };
  };
  await decryptEntity(entityId);
  if (entityId === "customers:customer_person_profile" || entityId === "customers:customer_company_profile") {
    await decryptEntity("customers:customer_entity");
  }
  return decryptIndexDocCustomFields(working, scope, service, cache);
}
async function encryptIndexDocForStorage(entityId, doc, scope, service) {
  if (!service || typeof service.encryptEntityPayload !== "function") return doc;
  if (service.isEnabled?.() === false) return doc;
  let working = doc;
  const encryptEntity = async (targetEntityId) => {
    const encrypted = await service.encryptEntityPayload(
      targetEntityId,
      working,
      scope.tenantId ?? null,
      scope.organizationId ?? null
    );
    working = { ...working, ...encrypted };
  };
  await encryptEntity(entityId);
  if (entityId === "customers:customer_person_profile" || entityId === "customers:customer_company_profile") {
    await encryptEntity("customers:customer_entity");
  }
  return working;
}
export {
  decryptIndexDocCustomFields,
  decryptIndexDocForSearch,
  encryptIndexDocForStorage
};
//# sourceMappingURL=indexDoc.js.map
