import { createHash } from 'node:crypto'

/**
 * Who receives Synchron's route emails for an HHA order (SW2, Synchron's
 * PUT /api/v1/hha/orders/{order_number}/notify-contacts; Nash 2026-10-07 item 4):
 * the buyers who are still on the trip, plus the trip's assigned carrier
 * drivers. A buyer who left the trip stops receiving them; people without an
 * email are left out; one entry per email address (purchaser wins over driver).
 *
 * Every change of the list gets a higher revision, and the Idempotency-Key is
 * built from the order, the revision and the list, so a retry of the same change
 * reuses its key while a new change (even back to an older list) gets a new one.
 */
export interface NotifyContact { name: string; email: string; role: 'purchaser' | 'driver' }

export function buildNotifyContacts(params: {
  purchasers: Array<{ name: string | null; email: string | null; stillOnTrip: boolean }>
  drivers: Array<{ name: string | null; email: string | null }>
}): NotifyContact[] {
  const byEmail = new Map<string, NotifyContact>()
  const add = (name: string | null, email: string | null, role: NotifyContact['role']) => {
    const clean = email?.trim().toLowerCase()
    if (!clean || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(clean)) return
    if (byEmail.get(clean)?.role === 'purchaser') return
    byEmail.set(clean, { name: name?.trim() || clean, email: clean, role })
  }
  for (const p of params.purchasers) if (p.stillOnTrip) add(p.name, p.email, 'purchaser')
  for (const d of params.drivers) add(d.name, d.email, 'driver')
  return [...byEmail.values()].sort((a, b) => a.role.localeCompare(b.role) * -1 || a.email.localeCompare(b.email))
}

/** True when the list differs from the one last sent (order and case don't matter). */
export function contactsChanged(previous: NotifyContact[] | null, next: NotifyContact[]): boolean {
  const canon = (list: NotifyContact[]) => JSON.stringify([...list].map((c) => [c.email, c.role, c.name]).sort())
  return previous === null || canon(previous) !== canon(next)
}

export function nextContactsRevision(previousRevision: number | null): number {
  return (previousRevision ?? 0) + 1
}

/** Stable per change: same order + revision + list → same key on every retry. */
export function contactsIdempotencyKey(orderNumber: string, revision: number, contacts: NotifyContact[]): string {
  const canon = JSON.stringify([...contacts].map((c) => [c.email, c.role, c.name]).sort())
  return createHash('sha256').update(`${orderNumber}|${revision}|${canon}`).digest('hex')
}
