import { MembershipLevelEnum } from "@scandic-hotels/common/constants/membershipLevels"

import { serverClient } from "@/lib/trpc/server"

import ProgressLevelCard from "./ProgressLevelCard"

import type { ProgressLevelWrapperProps } from "./types"

export default async function ProgressLevelWrapper({
  user,
}: ProgressLevelWrapperProps) {
  const caller = await serverClient()

  if (!user.membership || !user.membership.membershipLevel) {
    return null
  }

  // NOTE: We currently rely on the CMS to get "required_points" for a given level,
  // but API is working on including them in the Profile endpoint.
  const [currentLevel, nextLevel] = await Promise.all([
    caller.contentstack.loyaltyLevels.byLevel({
      level: MembershipLevelEnum[user.membership.membershipLevel],
    }),

    user.membership.nextLevel && MembershipLevelEnum[user.membership.nextLevel]
      ? caller.contentstack.loyaltyLevels.byLevel({
          level: MembershipLevelEnum[user.membership.nextLevel],
        })
      : null,
  ])

  const pointsToNextLevel = user.membership.pointsRequiredToNextlevel

  // Relying on user.loyalty.points.earned isn't suffice here as it isn't limited to loyalty-level specific earnings,
  // nor limited to earnings in the current member year.
  // TODO: API is working on adding a tierEarnings field which we'll be able to use for this.
  // Once that's out we won't need the nextLevel call above.
  const currentEarnings =
    nextLevel?.required_points && pointsToNextLevel
      ? nextLevel?.required_points - pointsToNextLevel
      : null

  let pointsNeededToKeepLevel = null

  if (currentEarnings !== null && currentLevel?.required_points) {
    if (currentEarnings < currentLevel.required_points) {
      pointsNeededToKeepLevel = currentLevel.required_points - currentEarnings
    }
  }

  return (
    <ProgressLevelCard
      pointsToNextLevel={pointsToNextLevel}
      pointsEarned={currentEarnings}
      pointsNeededToKeepLevel={pointsNeededToKeepLevel}
    />
  )
}
