"use server"

import { auth0 } from "@/lib/auth0"
import { markUserCompletedOnboarding, submitOnboardingQuestions } from "@codeflash-ai/common"
import PostHogClient from "@/lib/posthog"
import { redirect } from "next/navigation"
import { cookies } from "next/headers"

export async function SubmitFirstOnboardingPage(
  email: string,
  selectedOptions: string[],
  customOptionInput: string,
): 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.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,
    },
  })
  // PostHog batches automatically — no flush needed

  await submitOnboardingQuestions(user_id, email)
  // Check for saved redirect URL after onboarding completion
  const cookieStore = await cookies()
  const returnUrl = cookieStore.get("returnAfterOnboarding")?.value
  console.log("Checking for saved returnUrl:", returnUrl)
  if (returnUrl) {
    console.log("Found saved returnUrl, redirecting to:", returnUrl)
    cookieStore.delete("returnAfterOnboarding")
    redirect(returnUrl)
  } else {
    console.log("No saved returnUrl, redirecting to /app/gettingstarted")
    //redirect("/app")
  }
}

export async function SubmitSkipOnboardingPage(): 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.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,
    },
  })
  // PostHog batches automatically — no flush needed

  await markUserCompletedOnboarding(user_id)
  // Checking for saved redirect URL after onboarding completion
  const cookieStore = await cookies()
  const returnUrl = cookieStore.get("returnAfterOnboarding")?.value
  console.log(`Checking for saved returnTo URL: ${returnUrl}`)
  if (returnUrl) {
    console.log("Found saved returnUrl, redirecting to:", returnUrl)
    cookieStore.delete("returnAfterOnboarding")
    redirect(returnUrl)
  } else {
    console.log("No saved returnUrl, redirecting to /app/gettingstarted")
    //redirect("/app")
  }
}
