"use server"

import { getSession } from "@auth0/nextjs-auth0"
import { markUserCompletedOnboarding, submitOnboardingQuestions } from "@codeflash-ai/common/user-functions"
import PostHogClient from "@/app/app/posthog"
import { redirect } from "next/navigation"

export async function SubmitFirstOnboardingPage(
  email: string,
  selectedOptions: string[],
  customOptionInput: string,
): Promise<void> {
  const session = await 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()
  posthog.identify({
    distinctId: user_id,
    properties: {
      username: nickname,
      email: email,
      name: session?.user?.name,
    },
  })
  posthog.capture({
    distinctId: user_id,
    event: "webapp-onboarding-first-page-submitted",
    properties: {
      username: nickname,
      email: email,
      pain_points: selectedOptions,
      custom_pain_point: customOptionInput,
    },
  })
  await posthog.shutdown()

  await submitOnboardingQuestions(user_id, email)
}

export async function SubmitSkipOnboardingPage(
): Promise<void> {
  const session = await 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()
  posthog.identify({
    distinctId: user_id,
    properties: {
      username: nickname,
      name: session?.user?.name,
    },
  })
  posthog.capture({
    distinctId: user_id,
    event: "webapp-onboarding-first-page-submitted",
    properties: {
      username: nickname,
    },
  })
  await posthog.shutdown()

  await markUserCompletedOnboarding(user_id)
}