import { notFound } from "next/navigation"

import { combineRegExps, rateTypeRegex, REDEMPTION } from "@/constants/booking"

import SelectRate from "@/components/HotelReservation/SelectRate"
import { parseSelectRateSearchParams } from "@/utils/url"

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

const singleRoomRateTypes = combineRegExps(
  [rateTypeRegex.ARB, rateTypeRegex.VOUCHER],
  "i"
)

export default async function SelectRatePage(
  props: PageArgs<LangParams & { section: string }, NextSearchParams>
) {
  const params = await props.params
  const searchParams = await props.searchParams
  const booking = parseSelectRateSearchParams(searchParams)

  if (!booking) return notFound()

  const isMultiRoom = booking.rooms.length > 1
  const isRedemption = booking.searchType === REDEMPTION
  const isArbOrVoucher = booking.bookingCode
    ? singleRoomRateTypes.test(booking.bookingCode)
    : false

  if ((isMultiRoom && isRedemption) || (isMultiRoom && isArbOrVoucher)) {
    return notFound()
  }

  // If someone tries to update the url with
  // a bookingCode also, then we need to remove it
  if (isRedemption && searchParams.bookingCode) {
    delete searchParams.bookingCode
  }

  return <SelectRate lang={params.lang} booking={booking} />
}
