import { PROCEDURES, API_ROOT } from 'config'
import isEmpty from 'lodash/isEmpty'

import { client } from 'config/clients'

import type { MatchesBySection } from './types'
import { requestMatches } from './request'
import { getMatchesPreviews } from './getPreviews'

const proc = PROCEDURES.get_matches

export type TQueryParams = {
  arena?: Array<number>,
  division?: Array<number>,
  gender?: Array<number>,
  main_team?: Array<number>,
  round?: Array<number>,
  youth_age?: Array<number>,
}

type Args = {
  date: string,
  limit: number,
  offset: number,
  queryParams?: TQueryParams,
  timezoneOffset: number,
}

export const getHomeMatches = async ({
  date,
  limit,
  offset,
  queryParams,
  timezoneOffset,
}: Args): Promise<MatchesBySection> => {
  const url = `${API_ROOT}/v1/data/matches/query`
  const config = {
    body: {
      arena: !isEmpty(queryParams?.arena) ? queryParams?.arena : undefined,
      date: `${date} 00:00:00`,
      division: !isEmpty(queryParams?.division) ? queryParams?.division : undefined,
      gender: !isEmpty(queryParams?.gender) ? queryParams?.gender : undefined,
      gmt: String(timezoneOffset),
      limit: String(limit),
      main_team: !isEmpty(queryParams?.main_team) ? queryParams?.main_team : undefined,
      offset: String(offset),
      round: !isEmpty(queryParams?.round) ? queryParams?.round : undefined,
      youth_age: !isEmpty(queryParams?.youth_age) ? queryParams?.youth_age : undefined,
      ...client.requests?.[proc],
    },
  }

  return requestMatches(config, url).then(getMatchesPreviews)
}
