/**
 * Account contact details (Nash, 2026-09-23): the sign-in email can be
 * changed with a verification link; the phone can be changed any time.
 * Pure rules; the I/O is in src/lib/auth/accounts.ts and the account API.
 */

export interface IdentityOverride { email?: string | null; phone?: string | null; name?: string | null }

/** What the person's email and phone actually are: the account row wins over AUTH_USERS. */
export function effectiveIdentity<T extends { email: string; phone: string | null; name: string }>(env: T, override: IdentityOverride | null | undefined): T {
  if (!override) return env
  return {
    ...env,
    email: override.email?.trim() ? override.email.trim().toLowerCase() : env.email,
    phone: override.phone !== undefined && override.phone !== null ? override.phone.trim() || null : env.phone,
    name: override.name?.trim() ? override.name.trim() : env.name,
  }
}

export function normalizeEmailAddress(e: string): string {
  return e.trim().toLowerCase()
}

/** Is this email already someone else's? `known` = every email on the platform with its owner id. */
export function emailTaken(known: Array<{ email: string; userId: string }>, email: string, exceptUserId: string): boolean {
  const e = normalizeEmailAddress(email)
  return known.some((k) => normalizeEmailAddress(k.email) === e && k.userId !== exceptUserId)
}

/** A phone is stored as typed, lightly tidied; digits are kept for matching. */
export function tidyPhone(raw: string): { phone: string | null; digits: string | null } {
  const phone = raw.replace(/\s+/g, ' ').trim()
  if (!phone) return { phone: null, digits: null }
  const d = phone.replace(/\D/g, '')
  const digits = d.length === 11 && d.startsWith('1') ? d.slice(1) : d.length >= 10 ? d : null
  return { phone, digits }
}

/** After the sign-in email changes, a delivery address that simply mirrored the old one follows it. */
export function deliveryAfterEmailChange(deliveryEmail: string | null, oldEmail: string): string | null {
  if (!deliveryEmail) return null
  return normalizeEmailAddress(deliveryEmail) === normalizeEmailAddress(oldEmail) ? null : deliveryEmail
}
