import map from 'lodash/map'
import orderBy from 'lodash/orderBy'
import format from 'date-fns/format'

import type { User } from 'oidc-client'

import type { Match } from 'requests'

import { parseDate } from 'helpers/parseDate'

import { getMatchAccess } from './getMatchClickAction'

const prepareMatch = (match: Match, user?: User | undefined) => {
  const {
    calc,
    country,
    country_id,
    date: matchDate,
    group,
    has_video,
    id,
    is_finished,
    live,
    preview,
    previewURL,
    sport,
    sport_info,
    storage,
    team1,
    team2,
    tournament,
  } = match

  const date = parseDate(matchDate)
  return {
    access: getMatchAccess(match, user),
    calc,
    countryId: country_id,
    countryInfo: country,
    date,
    formattedDate: format(date, 'dd.MM.yy'),
    group,
    hasVideo: has_video,
    id,
    is_finished,
    live,
    preview,
    previewURL,
    sportInfo: sport_info,
    sportType: sport,
    storage,
    team1,
    team2,
    time: format(date, 'HH:mm'),
    tournament,
  }
}

export const prepareMatches = (matches: Array<Match>, user?: User | undefined) => {
  const preparedMatches = map(
    matches,
    (match) => prepareMatch(match, user),
  )
  return orderBy(
    preparedMatches,
    ['live'],
    ['desc'],
  )
}
