import isUndefined from 'lodash/isUndefined'

import { callApi } from 'helpers'

import { STATS_API_URL } from 'config'

export type Param = {
  clickable: boolean,
  data_type: string,
  id: number,
  lexic: number,
  markers: Array<number>,
  name_en: string,
  name_ru: string,
  val: number | null,
}

export type TeamStatItem = {
  lexic: number,
  name_en: string,
  name_ru: string,
  order: number,
  param1: Param,
  param2: Param | null,
}

type Response = {
  data?: {
    [teamId: string]: Array<TeamStatItem>,
  },
  error?: string,
  message?: string,
}

type GetTeamsStatsArgs = {
  matchId: number,
  period?: number,
  second?: number,
  sportName: string,
}

export const getTeamsStats = async ({
  matchId,
  period,
  second,
  sportName,
}: GetTeamsStatsArgs) => {
  const config = {
    method: 'GET',
  }

  const response: Response = await callApi({
    config,
    url: `${STATS_API_URL}/${sportName}/matches/${matchId}/teams/stats?group_num=0${isUndefined(second) ? '' : `&second=${second}&half=${period}`}`,
  })

  if (response.error) Promise.reject(response)

  return Promise.resolve(response.data || {})
}
