import map from 'lodash/map'
import sortBy from 'lodash/sortBy'

import type { MatchPlaylists, Players } from 'requests/getMatchPlaylists'

import type {
  Playlists,
  PlayerPlaylistOptions,
  MatchPlaylistOptions,
} from 'features/MatchPage/types'
import { PlaylistTypes } from 'features/MatchPage/types'

const MATCH_KEYS = [
  'full_game',
  'ball_in_play',
  'highlights',
  'goals',
] as const

export const FULL_GAME_KEY = MATCH_KEYS[0]
export type MatchPlaylistIds = typeof MATCH_KEYS[number]

const getMatchPlaylists = (matchPlaylists: MatchPlaylists | null): MatchPlaylistOptions => {
  if (!matchPlaylists) return []

  return map(MATCH_KEYS, (key) => {
    const playlist = matchPlaylists[key]
    const lexic = matchPlaylists.lexics[key] ?? ''
    return {
      duration: playlist?.dur,
      episodes: sortBy(playlist?.data, ['h', 's']),
      id: key,
      lexic,
      type: PlaylistTypes.MATCH,
    }
  })
}

const getPlayerPlaylists = (players?: Players): PlayerPlaylistOptions => (
  map(players, (player) => ({
    ...player,
    episodes: [],
    type: PlaylistTypes.PLAYER,
  }))
)

export const buildPlaylists = (matchPlaylists: MatchPlaylists | null) => {
  const playlists: Playlists = {
    interview: [],
    lexics: matchPlaylists?.lexics,
    match: getMatchPlaylists(matchPlaylists),
    players: {
      team1: getPlayerPlaylists(matchPlaylists?.players1),
      team2: getPlayerPlaylists(matchPlaylists?.players2),
    },
    score1: matchPlaylists?.score1 || 0,
    score2: matchPlaylists?.score2 || 0,
    state: matchPlaylists?.state,
  }
  return playlists
}
