"use server"
import { getSession } from "@auth0/nextjs-auth0"
import { BillingView } from "./billing-view"
import PostHogClient from "@/lib/posthog"
import { SUBSCRIPTION_PLANS, checkAndResetSubscriptionPeriod } from "@codeflash-ai/common"

export default async function BillingPage() {
  const session = await getSession()
  if (!session?.user) return null
  const userId = session.user.sub
  try {
    // Track page view
    const posthog = PostHogClient()
    posthog?.capture({
      distinctId: userId,
      properties: { username: session.user.nickname },
      event: "webapp-loaded-billing-page",
    })
    await posthog?.shutdown()

    // Get subscription info from database with lazy reset
    const subscription = (await checkAndResetSubscriptionPeriod(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} />
    )
  }
}
