import { useContext } from 'react'

import { GraphQLContext } from '../contexts/GraphQLContext'
import { Region } from '../graphql/__generated__/sdk'
import { useNetwork } from './useNetwork'

export function useRegions() {
  const g = useContext(GraphQLContext)

  const cacheKey = `regions`

  const response = g.useGetRegions(cacheKey, undefined, {
    shouldRetryOnError: false,
  })

  return useNetwork(response)
}

export function useRegion(countryCode: string): Region | undefined {
  const response = useRegions()
  const region = response.data?.regions.find(
    (region) => region.countryCode === countryCode
  )
  return region
}
