// cf-webapp/src/app/subscribe/pro/page.tsx
"use server"
import { Suspense } from "react"
import { auth0 } from "@/lib/auth0"
import { redirect } from "next/navigation"
import { createCheckoutSession } from "@codeflash-ai/common"
import * as Sentry from "@sentry/nextjs"

interface SearchParams {
  period?: "monthly" | "yearly"
}

async function SubscribeContent({ searchParams }: { searchParams: Promise<SearchParams> }) {
  const resolvedSearchParams = await searchParams
  const period: "monthly" | "yearly" = resolvedSearchParams.period || "monthly"
  const session = await auth0.getSession()

  if (!session) return null

  const userId = session.user.sub
  console.log(`Creating checkout for user ${userId} with period ${period}`)
  // Select price ID based on period
  const priceId =
    period === "yearly"
      ? process.env.STRIPE_PRO_PRICE_YEARLY_ID
      : process.env.STRIPE_PRO_PRICE_MONTHLY_ID
  if (!priceId) {
    throw new Error(`Stripe price ID is not defined for ${period} billing period.`)
  }
  // Generate checkout URL and redirect
  try {
    console.log(`Creating checkout for user ${userId} with period ${period} and priceId ${priceId}`)
    const baseUrl = process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000"
    const checkoutUrl = await createCheckoutSession(userId, priceId, {
      period,
      successUrl: `${baseUrl}/billing?success=true`,
      cancelUrl: `${baseUrl}/billing?canceled=true`,
    })
    // Ensure checkout URL is valid
    if (!checkoutUrl) {
      throw new Error("Generated checkout URL is empty or invalid")
    }
    console.log(`Redirecting to checkout URL: ${checkoutUrl}`)
    redirect(checkoutUrl)
  } catch (error) {
    Sentry.captureException(error)
    redirect("/billing?error=checkout_failed")
  }
}

export default async function ProSubscribePage(props: { searchParams: Promise<SearchParams> }) {
  return (
    <Suspense fallback={<div className="animate-pulse p-8">Loading...</div>}>
      <SubscribeContent searchParams={props.searchParams} />
    </Suspense>
  )
}
