import reduce from 'lodash/reduce'
import map from 'lodash/map'

import {
  DATA_URL,
  PROCEDURES,
  SportTypes,
} from 'config'
import { callApi } from 'helpers'

const proc = PROCEDURES.get_tournament_list

type Country = {
  id: number,
  name_eng: string,
  name_rus: string,
}

export type Tournament = {
  country: Country,
  gender: number | null,
  id: number,
  name_eng: string,
  name_rus: string,
  short_name_eng: string | null,
  short_name_rus: string | null,
  sport: SportTypes,
  tournament_type: number,
}

export type Tournaments = Array<Tournament>

const getSportTournaments = (sportId: SportTypes): Promise<Tournaments> => {
  const config = {
    body: {
      params: {
        _p_sport: sportId,
      },
      proc,
    },
  }

  return callApi({
    config,
    url: DATA_URL,
  })
}

export type TournamentsBySports = Partial<Record<SportTypes, Tournaments>>

export const getTournamentsBySports = async (sportIds: Array<SportTypes>) => {
  const responses = await Promise.all(map(sportIds, getSportTournaments))
  const tournamentsBySports = reduce(
    responses,
    (acc, curr) => {
      const { sport } = curr[0]
      acc[sport] = curr
      return acc
    },
    {} as TournamentsBySports,
  )
  return tournamentsBySports
}
