import { Suspense } from "react"
import { cacheLife, cacheTag } from "next/cache"
import { auth0 } from "@/lib/auth0"
import { BillingView } from "./billing-view"
import { trackBillingPageViewed } from "@/lib/analytics/tracking"
import { SUBSCRIPTION_PLANS, checkAndResetSubscriptionPeriod } from "@codeflash-ai/common"

async function getCachedSubscription(userId: string) {
  "use cache"
  cacheLife("frequent")
  cacheTag(`billing:${userId}`)

  const sub = await checkAndResetSubscriptionPeriod(userId)
  if (!sub) return null
  // Return plain object (no Prisma model) for cache serialization
  return {
    plan_type: sub.plan_type,
    optimizations_used: sub.optimizations_used,
    optimizations_limit: sub.optimizations_limit,
    subscription_status: sub.subscription_status,
    stripe_customer_id: sub.stripe_customer_id,
    stripe_subscription_id: sub.stripe_subscription_id,
    current_period_start: sub.current_period_start,
    current_period_end: sub.current_period_end,
  }
}

async function BillingContent() {
  const session = await auth0.getSession()
  if (!session?.user) return null
  const userId = session.user.sub
  try {
    // Track page view (fire-and-forget — batched by PostHog client)
    trackBillingPageViewed(userId, { username: session.user.nickname })

    // Get subscription info (cached 30s stale / 60s revalidate)
    const subscription = (await getCachedSubscription(userId)) || {
      plan_type: "free",
      optimizations_used: 0,
      optimizations_limit: SUBSCRIPTION_PLANS.FREE.optimizations,
      subscription_status: "active",
    }

    return <BillingView userId={userId} subscription={subscription} plans={SUBSCRIPTION_PLANS} />
  } catch (error) {
    console.error("Error fetching subscription:", error)

    // Provide fallback data in case of database errors
    const fallbackSubscription = {
      plan_type: "free",
      optimizations_used: 0,
      optimizations_limit: SUBSCRIPTION_PLANS.FREE.optimizations,
      subscription_status: "active",
    }

    return (
      <BillingView userId={userId} subscription={fallbackSubscription} plans={SUBSCRIPTION_PLANS} />
    )
  }
}

export default async function BillingPage() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <BillingContent />
    </Suspense>
  )
}
