"use server"

import { auth0 } from "@/lib/auth0"
import PostHogClient from "@/lib/posthog"
import { redirect } from "next/navigation"

export async function SubmitSecondOnboardingPage(
  teamSize: string | null,
  pythonUsage: string | null,
  pythonLibraries: string[] | null,
  colleagueInviteEmail: string | null,
): Promise<void> {
  const session = await auth0.getSession()
  if (session == null) {
    console.log("No session, redirecting to login")
    redirect("/login")
  }
  const user_id = session?.user?.sub
  const nickname = session?.user?.nickname
  const posthog = PostHogClient()
  if (!posthog) return

  posthog.capture({
    distinctId: user_id,
    event: "webapp-onboarding-second-page-submitted",
    properties: {
      username: nickname,
      ...(teamSize && { team_size: teamSize }),
      ...(pythonUsage && { python_usage: pythonUsage }),
      ...(pythonLibraries && pythonLibraries.length > 0 && { python_libraries: pythonLibraries }),
      ...(colleagueInviteEmail && { colleague_invite_email: colleagueInviteEmail }),
    },
  })
  // PostHog batches automatically — no flush needed
}
