import isEmpty from 'lodash/isEmpty'
import reduce from 'lodash/reduce'
import find from 'lodash/find'
import map from 'lodash/map'

import type { PreviewsData, Previews } from 'requests'
import { getMatchesPreviewImages } from 'requests'

import type { MatchesBySection, Matches } from './types'

const combinePreviews = (matches: Matches, previews: Previews) => (
  map(matches, (match) => {
    const preview = find(
      previews,
      { match_id: match.id, sport_id: match.sport },
    )?.preview
    return preview ? { ...match, preview } : match
  })
)

/**
 * Запрашивает превью картинок матчей с видео и статус которых Завершенный
 */
const getPreviews = async (matches: Matches) => {
  const previewsData = reduce(
    matches,
    (acc: PreviewsData, {
      has_video,
      id,
      sport,
    }) => {
      if (has_video) {
        acc.push({
          match_id: id,
          sport_id: sport,
        })
      }
      return acc
    },
    [],
  )

  if (isEmpty(previewsData)) return matches

  const previews = await getMatchesPreviewImages(previewsData)
  return combinePreviews(matches, previews)
}

export const getMatchesPreviews = async (matches: MatchesBySection) => {
  try {
    if (matches.isVideoSections) {
      const [
        broadcast,
        features,
        highlights,
      ] = await Promise.all(
        [
          getPreviews(matches.broadcast),
          getPreviews(matches.features),
          getPreviews(matches.highlights),
        ],
      )
      return {
        ...matches,
        broadcast,
        features,
        highlights,
      }
    }

    const broadcast = await getPreviews(matches.broadcast)

    return {
      ...matches,
      broadcast,
      features: [],
      highlights: [],
    }
  } catch (error) {
    return matches
  }
}
