import type { ComparisonLevel } from "@/types/components/overviewTable"
import type { CMSReward } from "@/types/trpc/routers/contentstack/reward"

export function getGroupedRewards(levels: ComparisonLevel[]) {
  const allRewards = levels
    .map((level) => {
      return level.rewards
    })
    .flat()

  const mappedRewards = allRewards.reduce<Record<string, CMSReward[]>>(
    (acc, curr) => {
      const taxonomiTerm = curr.taxonomies.find((tax) => tax.term_uid)?.term_uid

      if (taxonomiTerm) {
        if (!acc[taxonomiTerm]) {
          acc[taxonomiTerm] = []
        }
        acc[taxonomiTerm].push(curr)
      } else {
        if (!acc[curr.reward_id]) {
          acc[curr.reward_id] = []
        }
        acc[curr.reward_id].push(curr)
      }
      return acc
    },
    {}
  )

  return mappedRewards
}

export function findAvailableRewards(
  allRewardIds: string[],
  level: ComparisonLevel
) {
  return level.rewards.find((r) => allRewardIds.includes(r.reward_id))
}

export function getGroupedLabelAndDescription(rewards: CMSReward[]) {
  const reward = rewards.find((reward) => !!reward.grouped_label)
  return {
    label: reward?.grouped_label ?? "",
    description: reward?.grouped_description ?? "",
  }
}
