import type { Cache } from '@urql/exchange-graphcache'

function getTeamMilestones(cache: Cache, teamId: string) {
  const exercise = cache.resolve(
    cache.keyOfEntity({ __typename: 'TeamType', id: teamId }),
    'exercise'
  )
  if (typeof exercise === 'string') {
    const exerciseId = exercise.slice('ExerciseType:'.length)
    const milestoneStates = cache.resolve('Query', 'analyticsMilestones', {
      exerciseId,
    })
    if (Array.isArray(milestoneStates)) {
      return milestoneStates.filter(milestoneStateKey =>
        (cache.resolve(milestoneStateKey, 'teamIds') as string[]).includes(
          teamId
        )
      ) as string[]
    }
  }
}

export default getTeamMilestones
