export function matchesPatientSearch(encounter, query) {
  const trimmed = query.trim()
  if (!trimmed) return true

  const needle = trimmed.toLowerCase()
  const mrn = (encounter.mrn ?? '').toLowerCase()
  const firstName = (encounter.firstName ?? '').toLowerCase()
  const lastName = (encounter.lastName ?? '').toLowerCase()
  const fullName = `${firstName} ${lastName}`.trim()

  return (
    mrn.includes(needle)
    || firstName.includes(needle)
    || lastName.includes(needle)
    || fullName.includes(needle)
  )
}

function isSepsisActive(encounter) {
  return Boolean(encounter.sepsisActive || encounter.sepsisBundleStatus === 'IN_PROGRESS')
}

export function filterEncounters(
  encounters,
  { search = '', hasAlerts = false, sepsisActive = false, critical = false } = {},
) {
  return encounters.filter(encounter => {
    if (!matchesPatientSearch(encounter, search)) return false
    if (hasAlerts && !(encounter.openAlertCount > 0)) return false
    if (sepsisActive && !isSepsisActive(encounter)) return false
    if (critical && (encounter.news2Score ?? 0) < 7) return false
    return true
  })
}

export function hasWardFilters({ search = '', hasAlerts, sepsisActive, critical } = {}) {
  return Boolean(search.trim() || hasAlerts || sepsisActive || critical)
}
