import { cache } from "react"

import * as routes from "@/constants/routes/myPages"
import { env } from "@/env/server"

import { getIntl } from "@/i18n"
import { safeTry } from "@/utils/safeTry"
import { getEurobonusMembership } from "@/utils/user"

import type { UserLoyalty } from "@/types/user"
import type { Lang } from "@/constants/languages"
import type { MyPagesLink } from "./MyPagesLink"

export const getPrimaryLinks = cache(
  async ({
    lang,
    userLoyalty,
  }: {
    lang: Lang
    userLoyalty?: UserLoyalty
  }): Promise<MyPagesLink[]> => {
    const intl = await getIntl({ lang })

    const showSASLink = userLoyalty ? isScandicXSASActive(userLoyalty) : false
    const [showTeamMemberLink] = await safeTry(showTeamMemberCard())

    const menuItems: MyPagesLink[] = [
      {
        type: "link",
        text: intl.formatMessage({
          defaultMessage: "Overview",
        }),
        href: routes.overview[lang],
      },
      {
        type: "link",
        text: intl.formatMessage({
          defaultMessage: "My points",
        }),
        href: routes.points[lang],
      },
      {
        type: "link",
        text: intl.formatMessage({
          defaultMessage: "My stays",
        }),
        href: routes.stays[lang],
      },
      {
        type: "link",
        text: intl.formatMessage({
          defaultMessage: "My benefits",
        }),
        href: routes.benefits[lang],
      },
    ]

    if (showSASLink) {
      menuItems.push({
        type: "link",
        text: intl.formatMessage({
          defaultMessage: "Scandic ♥ SAS",
        }),
        href: routes.partnerSas[lang],
      })
    }

    if (showTeamMemberLink) {
      menuItems.push({
        type: "link",
        text: intl.formatMessage({
          defaultMessage: "Team Member Card",
        }),
        href: "#",
      })
    }

    return menuItems
  }
)

const isScandicXSASActive = (loyalty: UserLoyalty) => {
  const eurobonusMembership = getEurobonusMembership(loyalty)
  const isLinked = Boolean(eurobonusMembership)

  return env.SAS_ENABLED && isLinked
}

const showTeamMemberCard = cache(async () => {
  async function getIsTeamMember() {
    // TODO: Implement this check
    return false
  }

  const isTeamMember = await getIsTeamMember()
  return isTeamMember
})
