import { findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { CustomerEntity } from "../data/entities.js";
function normalizeAddresses(input) {
  if (!Array.isArray(input)) return [];
  const seen = /* @__PURE__ */ new Set();
  const out = [];
  for (const value of input) {
    if (typeof value !== "string") continue;
    const trimmed = value.trim().toLowerCase();
    if (!trimmed) continue;
    const at = trimmed.indexOf("@");
    if (at <= 0 || at === trimmed.length - 1 || trimmed.lastIndexOf("@") !== at) continue;
    if (seen.has(trimmed)) continue;
    seen.add(trimmed);
    out.push(trimmed);
  }
  return out;
}
const MATCH_CANDIDATE_LIMIT = 500;
async function findPeopleByAddresses(em, addresses, tenantId, organizationId = null) {
  const normalized = normalizeAddresses(addresses);
  if (normalized.length === 0) return [];
  if (!organizationId) return [];
  const dscope = { tenantId, organizationId };
  const resolved = /* @__PURE__ */ new Map();
  const direct = await findWithDecryption(
    em,
    CustomerEntity,
    { primaryEmail: { $in: normalized }, kind: "person", tenantId, organizationId, deletedAt: null },
    void 0,
    dscope
  );
  for (const row of direct) {
    const rowEmail = row.primaryEmail?.trim().toLowerCase();
    if (rowEmail && !resolved.has(rowEmail)) resolved.set(rowEmail, row.id);
  }
  if (normalized.some((email) => !resolved.has(email))) {
    const candidates = await findWithDecryption(
      em,
      CustomerEntity,
      { kind: "person", tenantId, organizationId, deletedAt: null },
      { limit: MATCH_CANDIDATE_LIMIT, orderBy: { createdAt: "DESC" } },
      dscope
    );
    for (const row of candidates) {
      const rowEmail = row.primaryEmail?.trim().toLowerCase();
      if (rowEmail && !resolved.has(rowEmail)) resolved.set(rowEmail, row.id);
    }
  }
  const seen = /* @__PURE__ */ new Set();
  const out = [];
  for (const email of normalized) {
    const id = resolved.get(email);
    if (!id || seen.has(id)) continue;
    seen.add(id);
    out.push({ id, email });
  }
  return out;
}
export {
  findPeopleByAddresses,
  normalizeAddresses
};
//# sourceMappingURL=findPeopleByAddresses.js.map
