import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
const normalizeDigits = (value) => value.replace(/\D+/g, "");
const MAX_PAGES = 3;
const PAGE_SIZE = 50;
async function lookupPhoneDuplicate(rawDigits, { recordId } = {}) {
  const digits = normalizeDigits(rawDigits);
  if (!digits) return null;
  const seen = /* @__PURE__ */ new Set();
  for (let page = 1; page <= MAX_PAGES; page += 1) {
    try {
      const url = `/api/customers/people?hasPhone=true&page=${page}&pageSize=${PAGE_SIZE}&sortField=createdAt&sortDir=desc`;
      const call = await apiCall(url);
      if (!call.ok) continue;
      const payload = call.result ?? {};
      const items = Array.isArray(payload?.items) ? payload.items : [];
      for (const item of items) {
        if (!item || typeof item !== "object") continue;
        const record = item;
        const id = typeof record.id === "string" ? record.id : null;
        if (!id || seen.has(id)) continue;
        seen.add(id);
        if (recordId && id === recordId) continue;
        const displayName = typeof record.display_name === "string" ? record.display_name : null;
        const phoneRaw = typeof record.primary_phone === "string" ? record.primary_phone : "";
        const itemDigits = normalizeDigits(phoneRaw);
        if (!displayName || !itemDigits) continue;
        if (itemDigits === digits) {
          return {
            id,
            label: displayName,
            href: `/backend/customers/people/${id}`
          };
        }
      }
      const total = typeof payload?.total === "number" ? payload.total : null;
      if (total !== null && page * PAGE_SIZE >= total) {
        break;
      }
    } catch {
    }
  }
  return null;
}
export {
  lookupPhoneDuplicate
};
//# sourceMappingURL=phoneDuplicates.js.map
