import { encryptWithAesGcm, decryptWithAesGcm } from "./aes.js";
import { TenantDataEncryptionService } from "./tenantDataEncryptionService.js";
const STRING_TYPED_CUSTOM_FIELD_KINDS = /* @__PURE__ */ new Set([
  "text",
  "multiline",
  "select",
  "currency",
  "dictionary",
  "phone",
  "email",
  "url",
  "string"
]);
function shouldPreserveAsString(kind) {
  if (!kind) return false;
  return STRING_TYPED_CUSTOM_FIELD_KINDS.has(kind);
}
const serviceCache = /* @__PURE__ */ new WeakMap();
function resolveTenantEncryptionService(em, provided) {
  if (provided) return provided;
  const cached = serviceCache.get(em);
  if (cached) return cached;
  const service = new TenantDataEncryptionService(em);
  serviceCache.set(em, service);
  return service;
}
async function resolveDekKey(service, tenantId, cache, opts) {
  const scopedTenantId = tenantId ?? null;
  if (!service || !service.isEnabled() || !scopedTenantId) return null;
  if (cache?.has(scopedTenantId)) return cache.get(scopedTenantId) ?? null;
  const dek = await service.getDek(scopedTenantId);
  let key = dek?.key ?? null;
  if (!key && opts?.createIfMissing && typeof service.createDek === "function") {
    const created = await service.createDek(scopedTenantId);
    key = created?.key ?? null;
  }
  cache?.set(scopedTenantId, key);
  return key;
}
async function encryptCustomFieldValue(value, tenantId, service, cache) {
  if (value === void 0 || value === null) return value;
  const key = await resolveDekKey(service, tenantId, cache, { createIfMissing: true });
  if (!key) return value;
  const serialized = typeof value === "string" ? value : JSON.stringify(value);
  return encryptWithAesGcm(serialized, key).value;
}
async function decryptCustomFieldValue(value, tenantId, service, cache, options) {
  if (value === void 0 || value === null || typeof value !== "string") return value;
  const key = await resolveDekKey(service, tenantId, cache);
  if (!key) return value;
  const decrypted = decryptWithAesGcm(value, key);
  if (decrypted === null) return value;
  if (shouldPreserveAsString(options?.kind ?? null)) return decrypted;
  try {
    return JSON.parse(decrypted);
  } catch {
    return decrypted;
  }
}
export {
  decryptCustomFieldValue,
  encryptCustomFieldValue,
  resolveTenantEncryptionService
};
//# sourceMappingURL=customFieldValues.js.map
