import { redirect } from "next/navigation"
import React from "react"

import { getProfileSafely } from "@/lib/trpc/memoizedRequests"

import { getEurobonusMembership } from "@/utils/user"

import { SASModal } from "../components/SASModal"
import { LinkAccountForm } from "./LinkAccountForm"

import type { LangParams, PageArgs } from "@/types/params"

export default async function SASxScandicLinkPage(props: PageArgs<LangParams>) {
  const params = await props.params;
  const profile = await getProfileSafely()

  if (!profile || !profile.loyalty) return null

  const eurobonusMembership = getEurobonusMembership(profile.loyalty)

  if (eurobonusMembership) {
    redirect(`/${params.lang}/sas-x-scandic/error?errorCode=alreadyLinked`)
  }

  return (
    <SASModal>
      <LinkAccountForm userDateOfBirth={profile?.dateOfBirth ?? null} />
    </SASModal>
  )
}
