import type { FullContact } from "./types"

export function normalizeEmail(email: string): string {
  return email.trim().toLowerCase()
}

export function findContactByEmail(
  contacts: FullContact[],
  email: string,
): FullContact | undefined {
  const norm = normalizeEmail(email)
  if (!norm) return undefined
  return contacts.find((c) =>
    c.emails.some((e) => normalizeEmail(e.value) === norm),
  )
}

/** Split display name into first / last for create form prefill. */
export function parseDisplayNameToNameParts(displayName: string): {
  firstName: string
  lastName: string
} {
  const clean = displayName.trim()
  if (!clean) return { firstName: "", lastName: "" }
  const space = clean.indexOf(" ")
  if (space === -1) return { firstName: clean, lastName: "" }
  return {
    firstName: clean.slice(0, space),
    lastName: clean.slice(space + 1).trim(),
  }
}
