import { z } from "zod"

import {
  MembershipLevel,
  MembershipLevelEnum,
} from "@/constants/membershipLevels"
import { getMembershipCardsSchema } from "@/server/routers/user/output"

import type { Membership, Memberships, User } from "@/types/user"

enum scandicMemberships {
  guestpr = "guestpr",
  scandicfriends = "scandicfriend's",
}

export function getMembership(memberships: Memberships) {
  return memberships?.find(
    (membership) =>
      membership.membershipType.toLowerCase() === scandicMemberships.guestpr
  ) as FriendsMembership | undefined
}

export type FriendsMembership = Omit<
  NonNullable<Membership>,
  "membershipLevel" | "nextLevel"
> & {
  membershipLevel: MembershipLevel
  nextLevel: MembershipLevel
}

export function getMembershipCards(
  memberships: z.infer<typeof getMembershipCardsSchema>
) {
  return memberships.filter(function (membership) {
    return (
      membership.membershipType.toLowerCase() !== scandicMemberships.guestpr &&
      membership.membershipType.toLowerCase() !==
        scandicMemberships.scandicfriends
    )
  })
}

export function isHighestMembership(
  membershipLevel: MembershipLevel | undefined
) {
  return membershipLevel == MembershipLevelEnum.L7
}

export function getInitials(
  firstName: User["firstName"],
  lastName: User["lastName"]
) {
  if (!firstName || !lastName) return null
  const firstInitial = firstName.charAt(0).toUpperCase()
  const lastInitial = lastName.charAt(0).toUpperCase()
  return `${firstInitial}${lastInitial}`
}

export function getSteppedUpLevel(
  currentValue: MembershipLevel,
  stepsUp: number
): MembershipLevel {
  const values = Object.values(MembershipLevelEnum)
  const currentIndex = values.indexOf(currentValue as MembershipLevelEnum)
  if (currentIndex === -1 || currentIndex === values.length - 1) {
    return currentValue
  }
  return values[currentIndex + stepsUp]
}
