import map from 'lodash/map'

import { currencySymbols } from 'config'

import type {
  SubscriptionsByPeriods,
  Subscriptions,
} from 'requests/getSubscriptions'

import { getName } from 'features/Name'

import type {
  MatchSubscriptions,
  MatchSubscription,
  Match,
} from '../types'
import { SubscriptionType } from '../types'
import {
  passLexics,
  passNameKeys,
  descriptionLexics,
} from './config'

type SubscriptionArgs = {
  match: Match,
  subscriptions: SubscriptionsByPeriods,
  suffix: string,
}

const transformSubscription = ({
  match,
  subscriptions,
  suffix,
}: SubscriptionArgs) => (
  type: SubscriptionType.Month | SubscriptionType.Year,
): Array<MatchSubscription> => {
  const { season } = subscriptions
  return map(subscriptions[type], (subscription, rawKey) => {
    const key = rawKey as keyof Subscriptions
    const teamName = getName({
      nameObj: match[passNameKeys[key]],
      suffix,
    })
    return {
      currency: currencySymbols[subscription.currency_iso],
      description: {
        lexic: descriptionLexics[key],
        values: {
          season: season.name,
          team: teamName,
        },
      },
      id: `${key} ${subscription.sub.id}`,
      name: teamName,
      originalObject: subscription,
      pass: passLexics[key],
      price: subscription.price,
      seasonName: season.name,
      type,
    }
  })
}

type SubsciptionsArgs = {
  match: Match,
  subscriptions: SubscriptionsByPeriods,
  suffix: string,
}

export const transformSubsciptions = ({
  match,
  subscriptions,
  suffix,
}: SubsciptionsArgs): MatchSubscriptions => {
  const { pay_per_view: payPerView } = subscriptions
  const team1Name = getName({ nameObj: match.team1, suffix })
  const team2Name = getName({ nameObj: match.team2, suffix })
  const transformByType = transformSubscription({
    match,
    subscriptions,
    suffix,
  })

  return {
    [SubscriptionType.Month]: transformByType(SubscriptionType.Month),
    [SubscriptionType.Year]: transformByType(SubscriptionType.Year),
    [SubscriptionType.PayPerView]: subscriptions.pay_per_view ? ([{
      currency: currencySymbols[payPerView?.currency_iso],
      description: {
        lexic: 'description_match_live_and_on_demand',
        values: {},
      },
      id: '0',
      name: `${team1Name} - ${team2Name}`,
      originalObject: payPerView,
      pass: 'pass_match_access',
      price: payPerView?.price,
      type: SubscriptionType.PayPerView,
    }]) : [],
  }
}
