export interface PersonIdentity {
  email?: string | null;
  phone?: string | null;
  kycIdNumber?: string | null;
}

const emailKey = (value: string | null | undefined) => value?.trim().toLowerCase() || null;
export const phoneKey = (value: string | null | undefined) => {
  const digits = value?.replace(/\D/g, '') ?? '';
  return digits.length >= 7 ? digits.slice(-10) : null;
};
const idKey = (value: string | null | undefined) => value?.replace(/\s/g, '').toUpperCase() || null;

/** The stable identifier that proves two customer records are the same person. */
export function duplicateIdentityField(input: PersonIdentity, existing: PersonIdentity): 'email' | 'phone' | 'ID number' | null {
  const email = emailKey(input.email);
  if (email && email === emailKey(existing.email)) return 'email';
  const phone = phoneKey(input.phone);
  if (phone && phone === phoneKey(existing.phone)) return 'phone';
  const id = idKey(input.kycIdNumber);
  if (id && id === idKey(existing.kycIdNumber)) return 'ID number';
  return null;
}
