import { type Period, isPeriodActive } from './periodUtils'

interface ContactPoint {
  system?: String
  use?: String
  rank?: Number
  period?: Period
  value?: String
}

export function getContactPoints(
  contact: ContactPoint[],
  system: 'phone' | 'email' | 'url' | 'fax' | 'pager' | 'sms' | 'other',
): String[] {
  if (!contact || contact.length === 0) {
    return []
  }

  // Filter contact points by the specified system
  const filteredBySystem = contact.filter((cp) => cp.system === system)

  if (filteredBySystem.length === 0) {
    return []
  }

  // Filter active contact points using the exported function
  const activeContactPoints = filteredBySystem.filter((cp) =>
    isPeriodActive(cp.period),
  )

  let sortedContactPoints: ContactPoint[]
  if (activeContactPoints.length > 0) {
    // Sort active contact points by rank (lower rank is preferred)
    activeContactPoints.sort(
      (a, b) => (a.rank || Infinity) - (b.rank || Infinity),
    )
    sortedContactPoints = activeContactPoints
  } else {
    // If no active contact points, return all contact points for the system sorted by rank
    filteredBySystem.sort((a, b) => (a.rank || Infinity) - (b.rank || Infinity))
    sortedContactPoints = filteredBySystem
  }

  // Map the sorted ContactPoint array to an array of their 'value' properties
  return sortedContactPoints.map((cp) => cp.value || '')
}
