import isNull from 'lodash/isNull'
import filter from 'lodash/filter'

import {
  ProfileTypes,
  SportTypes,
  PROFILE_NAMES,
} from 'config'

import {
  Gender,
  getSearchItems,
  SearchItems,
} from './getSearchItems'

type FilterArgs = {
  gender: Gender | null,
  profileType: ProfileTypes | null,
  results: SearchItems,
  sportType: SportTypes | null,
}

type Item = {
  gender?: Gender,
  sport: SportTypes,
}

// этот хелпер и его типы удалим когда сделают
// норм процу с фильтрацией по полу, профилю и спорту
const filterResults = ({
  gender,
  profileType,
  results,
  sportType,
}: FilterArgs) => {
  const filterFunc = (item: Item) => {
    let result = true
    if (!isNull(gender)) {
      result = item.gender === gender
    }
    if (!isNull(sportType)) {
      result = item.sport === sportType
    }
    return result
  }

  const filteredResults = {
    players: filter(results.players, filterFunc),
    supertournaments: '',
    teams: filter(results.teams, filterFunc),
    tournaments: filter(results.tournaments, filterFunc),
  }

  if (isNull(profileType) || profileType === ProfileTypes.MATCHES) return filteredResults

  const key = PROFILE_NAMES[profileType]
  return { [key]: filteredResults[key] }
}

type Args = {
  abortSignal: AbortSignal,
  gender: Gender | null,
  profileType: ProfileTypes | null,
  query: string,
  sportType: SportTypes | null,
}

export const extendedSearch = async ({
  abortSignal,
  gender,
  profileType,
  query,
  sportType,
}: Args) => {
  const results = await getSearchItems(query, abortSignal)
  return filterResults({
    gender,
    profileType,
    results,
    sportType,
  })
}
