import { Lang } from "@/constants/languages"
import { profile } from "@/constants/routes/myPages"
import { serverClient } from "@/lib/trpc/server"
import { getPublicURL } from "@/server/utils"

import type { NextRequest } from "next/server"

export async function GET(
  request: NextRequest,
  props: { params: Promise<{ lang: string }> }
) {
  const params = await props.params
  const publicURL = getPublicURL(request)

  console.log(`[add-card] callback started`)
  const lang = params.lang as Lang
  const returnUrl = new URL(`${publicURL}/${profile[lang ?? Lang.en]}`)

  try {
    const searchParams = request.nextUrl.searchParams
    const success = searchParams.get("success")
    const failure = searchParams.get("failure")
    const cancel = searchParams.get("cancel")
    const trxId = searchParams.get("datatransTrxId")

    if (success) {
      if (trxId) {
        const caller = await serverClient()
        const saveCardSuccess = await caller.user.creditCard.save({
          transactionId: trxId,
        })

        if (saveCardSuccess) {
          console.log(`[add-card] planet success: card saved success`)
          returnUrl.searchParams.set("success", "true")
        } else {
          console.log(`[add-card] planet success: card saved fail`)
          returnUrl.searchParams.set("failure", "true")
        }
      } else {
        console.log(`[add-card] planet success: missing datatransTrxId`)
        returnUrl.searchParams.set("error", "true")
      }
    } else if (failure) {
      console.log(`[add-card] planet fail`)
      returnUrl.searchParams.set("failure", "true")
    } else if (cancel) {
      console.log(`[add-card] planet cancel`)
      returnUrl.searchParams.set("cancel", "true")
    }
  } catch (e) {
    console.error(`[add-card] error saving credit card`, e)
    returnUrl.searchParams.set("error", "true")
  }

  console.log(`[add-card] redirecting to: ${returnUrl}`)
  return Response.redirect(returnUrl)
}
