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

import { MatchStatuses } from 'features/HeaderFilters'

const proc = PROCEDURES.get_matches

export type Data = {
  is_video_sections: boolean,
  video_content: VideoContent,
}

export type VideoContent = {
  broadcast: Items,
  features: Items,
  highlights: Items,
}

export type Items = {
  content: Array<Content> | null,
  name: string,
}

export type Content = {
  id: number,
  matches: Array<Match>,
  name_eng: string,
  name_rus: string,
  sport: 1 | 2 | 3,
}

export type Match = {
  date: string,
  id: number,
  round_id: number | null,
  stream_status: number,
  team1: Team,
  team2: Team,
}

export type Team = {
  id: number,
  name_eng: string,
  name_rus: string,
  score: number,
}

type Args = {
  date: string,
  matchStatus: MatchStatuses,
  sportType: SportTypes,
  tournamentId: number | null,
}

export type Matches = {
  broadcast: Array<Content>,
  features: Array<Content>,
  highlights: Array<Content>,
  isVideoSections: boolean,
}

export const getMatches = async ({
  date,
  matchStatus,
  sportType,
  tournamentId,
}: Args) => {
  const config = {
    body: {
      params: {
        _p_date: date,
        _p_sport: sportType,
        _p_stream_status: matchStatus,
        _p_tournament_id: tournamentId,
      },
      proc,
    },
  }

  const data: Data = await callApi({
    config,
    url: DATA_URL,
  }).then(getResponseData(proc))

  const {
    broadcast,
    features,
    highlights,
  } = data.video_content

  return {
    broadcast: broadcast.content || [],
    features: features.content || [],
    highlights: highlights.content || [],
    isVideoSections: data.is_video_sections,
  }
}
