import map from 'lodash/map'
import orderBy from 'lodash/orderBy'

import format from 'date-fns/format'

import type { User } from 'oidc-client'

import type { MatchDto } from 'requests'

import { parseDate } from 'helpers/parseDate'

import { getMatchAccess } from 'features/Matches/helpers/getMatchClickAction'

export type Match = ReturnType<typeof prepareMatch>

const prepareMatch = (match: MatchDto, 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<MatchDto>,
  user?: User | undefined,
  liveOrder: boolean = true,
): Array<Match> => {
  const preparedMatches = map(
    matches,
    (match) => prepareMatch(match, user),
  )

  if (liveOrder) {
    return orderBy(
      preparedMatches,
      ['live'],
      ['desc'],
    )
  }
  return preparedMatches
}
