import crypto from 'node:crypto' export function canonicalWhatsAppJid(jid, identity = {}) { const normalizeDevice = (value) => String(value || '') .trim() .toLowerCase() .replace(/:\d+(?=@s\.whatsapp\.net$)/, '') const raw = normalizeDevice(jid) if (!raw || raw.endsWith('@g.us') || raw.endsWith('@newsletter')) return raw const canonical = normalizeDevice(identity?.canonicalJid) if (canonical.endsWith('@s.whatsapp.net')) return canonical const phone = String(identity?.phone || '').split(':')[0].replace(/\D/g, '') return phone ? `${phone}@s.whatsapp.net` : raw } export function resolvedWhatsAppJid(jid, identity = {}, cachedJid = '') { const fallback = canonicalWhatsAppJid(jid) const resolved = canonicalWhatsAppJid(jid, identity) if (resolved && resolved !== fallback) return resolved const cached = canonicalWhatsAppJid(cachedJid) return cached && cached !== fallback ? cached : fallback } export function whatsappCustomerStableId(jid) { const normalized = canonicalWhatsAppJid(jid) const hash = crypto.createHash('sha256').update(normalized).digest('hex').slice(0, 24) return `wa-customer-${hash}` } export function whatsappConversationActivityAt(conversation) { return Date.parse( conversation?.lastMessage?.createdAt || conversation?.updatedAt || conversation?.createdAt || '', ) || 0 } export function isWeakWhatsAppDisplayName(value, jid) { const name = String(value || '').trim() const jidName = String(jid || '').split('@')[0].replace(/\D/g, '') const digits = name.replace(/\D/g, '') return !name || (digits.length >= 7 && (!jidName || digits === jidName)) } export function reusableWhatsAppConversations(conversations, activeChannelIds, channelId, jid) { return conversations .filter((item) => ( item.channel === 'whatsapp' && String(item.whatsappJid || '') === String(jid) && ( String(item.channelId || '') === String(channelId) || !activeChannelIds.has(String(item.channelId || String(item.id).split(':')[0])) ) )) .sort((left, right) => whatsappConversationActivityAt(right) - whatsappConversationActivityAt(left)) }