import type { Match } from 'features/BuyMatchPopup/types'

import { checkUrlParams, getAllUrlParams } from '../parseUrlParams/parseUrlParams'
import { getMatchInfo, MatchInfo } from '../../requests'
import { prepareMatchProfile } from '../../features/MatchPage/helpers/prepareMatchProfile'

type openSubscribePopupType = {
  matchConfig: {
    matchId: number,
    sportId: number,
  },
  openBuyMatchPopup: (matchProfile: Match) => void,
}

// TODO переделать потом на открытие без запроса матча
export const openSubscribePopup = ({
  matchConfig,
  openBuyMatchPopup,
}: openSubscribePopupType) => {
  if (isSubscribePopup()) {
    getMatchInfo(matchConfig.sportId, matchConfig.matchId)
      .then((match: MatchInfo) => {
        const matchProfile = match && prepareMatchProfile({
          matchId: matchConfig.matchId,
          profile: match,
          sportType: matchConfig.sportId,
        })
        matchProfile && openBuyMatchPopup(matchProfile)
      })
  }
}

export const isSubscribePopup = () => checkUrlParams('subscribe') && getAllUrlParams('id').length
