import isUndefined from 'lodash/isUndefined'

import { SportTypes, STATS_API_URL } from 'config'

import { callApi } from 'helpers'

export type Player = {
  birthday: string | null,
  c_country: number,
  c_gender: number,
  club_f_team: number,
  club_shirt_num: number,
  firstname_eng: string,
  firstname_national: string | null,
  firstname_rus: string,
  height: number | null,
  id: number,
  is_gk: boolean,
  lastname_eng: string,
  lastname_national: string | null,
  lastname_rus: string,
  national_f_team: number | null,
  national_shirt_num: number,
  nickname_eng: string | null,
  nickname_rus: string | null,
  num: number | null,
  ord: number,
  weight: number | null,
}

type DataItem = {
  players: Array<Player>,
  team_id: number,
}

type Response = {
  data?: Array<DataItem>,
  error?: {
    code: string,
    message: string,
  },
}

type GetMatchParticipantsArgs = {
  matchId: number,
  period?: number,
  second?: number,
  sportType: SportTypes,
}

export const getMatchParticipants = async ({
  matchId,
  period,
  second,
  sportType,
}: GetMatchParticipantsArgs) => {
  const config = {
    method: 'GET',
  }

  const response: Response = await callApi({
    config,
    url: `${STATS_API_URL}/ask/participants?sport_id=${sportType}&match_id=${matchId}${isUndefined(second) ? '' : `&second=${second}&half=${period}`}`,
  })

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

  return Promise.resolve(response.data || [])
}
