import { NextRequest, NextResponse } from "next/server"

import { BOOKING_CONFIRMATION_NUMBER } from "@/constants/booking"
import { Lang } from "@/constants/languages"
import {
  bookingConfirmation,
  payment,
} from "@/constants/routes/hotelReservation"
import { getPublicURL } from "@/server/utils"

export async function GET(
  request: NextRequest,
  { params }: { params: { lang: string; status: string } }
): Promise<NextResponse> {
  const publicURL = getPublicURL(request)

  console.log(`[payment-callback] callback started`)
  const lang = params.lang as Lang
  const status = params.status

  const queryParams = request.nextUrl.searchParams
  const confirmationNumber = queryParams.get(BOOKING_CONFIRMATION_NUMBER)

  if (status === "success" && confirmationNumber) {
    const confirmationUrl = new URL(`${publicURL}/${bookingConfirmation[lang]}`)
    confirmationUrl.searchParams.set(
      BOOKING_CONFIRMATION_NUMBER,
      confirmationNumber
    )

    console.log(`[payment-callback] redirecting to: ${confirmationUrl}`)
    return NextResponse.redirect(confirmationUrl)
  }

  const returnUrl = new URL(`${publicURL}/${payment[lang]}`)
  returnUrl.search = queryParams.toString()

  if (status === "cancel") {
    returnUrl.searchParams.set("cancel", "true")
  }

  if (status === "error") {
    returnUrl.searchParams.set("error", "true")
  }

  console.log(`[payment-callback] redirecting to: ${returnUrl}`)
  return NextResponse.redirect(returnUrl)
}
