import includes from 'lodash/includes'
import toLower from 'lodash/toLower'
import reduce from 'lodash/reduce'
import filter from 'lodash/filter'

import type { SportTypes } from 'config'
import type { TournamentsBySports, Tournaments } from 'requests/getSportTournaments'

const getFlatTournaments = (
  tournamentsBySports: TournamentsBySports,
  selectedSports: Array<SportTypes>,
) => (
  reduce(
    selectedSports,
    (acc, sport) => {
      const sportTournaments = tournamentsBySports[sport]
      if (sportTournaments) {
        return [...acc, ...sportTournaments]
      }
      return acc
    },
    [] as Tournaments,
  )
)

type NameKey = 'name_eng' | 'name_rus'

type SearchProps = {
  query: string,
  selectedSports: Array<SportTypes>,
  suffix: string,
  tournamentsBySports: TournamentsBySports,
}

export const search = async ({
  query,
  selectedSports,
  suffix,
  tournamentsBySports,
}: SearchProps) => {
  const tournaments = getFlatTournaments(tournamentsBySports, selectedSports)
  const nameKey = `name_${suffix}` as NameKey
  return filter(
    tournaments,
    (tournament) => includes(
      toLower(tournament[nameKey]),
      toLower(query),
    ),
  )
}
