import type { User } from '@inject/graphql/fragment-types'

type FilterUsersProps = {
  users: User[]
} & (
  | {
      searchString?: string
      predicate?: never
    }
  | {
      searchString?: never
      predicate: (user: User) => boolean
    }
)

const useFilterUsers = ({
  users,
  searchString,
  predicate,
}: FilterUsersProps): User[] => {
  if (predicate) return users.filter(predicate)

  if (!searchString) return users

  const insensitiveSearchString = searchString.toLowerCase()

  return users.filter(
    user =>
      user.username.toLowerCase().includes(insensitiveSearchString) ||
      user.firstName?.toLowerCase().includes(insensitiveSearchString) ||
      user.lastName?.toLowerCase().includes(insensitiveSearchString)
  )
}

export default useFilterUsers
