import { cookies } from "next/headers"
import { notFound, redirect } from "next/navigation"

import { MEMBERSHIP_FAILED_ERROR } from "@/constants/booking"
import { getBookingConfirmation } from "@/lib/trpc/memoizedRequests"

import BookingConfirmation from "@/components/HotelReservation/BookingConfirmation"
import { decrypt } from "@/utils/encryption"

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

export default async function BookingConfirmationPage(
  props: PageArgs<LangParams, { RefId?: string }>
) {
  const searchParams = await props.searchParams
  const params = await props.params
  const refId = searchParams.RefId

  if (!refId) {
    notFound()
  }

  const cookieStore = await cookies()
  const sig = cookieStore.get("bcsig")?.value

  if (!sig) {
    redirect(`/${params.lang}`)
  }

  const expire = Number(decrypt(sig))
  const now = Math.floor(Date.now() / 1000)
  if (typeof expire === "number" && !isNaN(expire) && now > expire) {
    redirect(`/${params.lang}`)
  }

  void getBookingConfirmation(refId)

  const membershipFailedError =
    searchParams.errorCode === MEMBERSHIP_FAILED_ERROR

  return (
    <BookingConfirmation
      refId={refId}
      membershipFailedError={membershipFailedError}
    />
  )
}
