/**
 * Canonicalize an email address for identity deduplication.
 *
 * Gmail / Googlemail rules:
 *   - dots in local-part are ignored (j.o.h.n == john)
 *   - plus-suffix is stripped (john+spam@gmail.com == john@gmail.com)
 *   - googlemail.com is an alias for gmail.com
 *
 * All other providers: lowercase only.
 */
export function canonicalizeEmail(raw: string): string {
  const lower = raw.trim().toLowerCase()
  const atIdx = lower.lastIndexOf('@')
  if (atIdx === -1) return lower

  let local = lower.slice(0, atIdx)
  let domain = lower.slice(atIdx + 1)

  if (domain === 'googlemail.com') domain = 'gmail.com'

  if (domain === 'gmail.com') {
    const plusIdx = local.indexOf('+')
    if (plusIdx !== -1) local = local.slice(0, plusIdx)
    local = local.replace(/\./g, '')
  }

  return `${local}@${domain}`
}
