"use server"
import { redirect } from "next/navigation"
import { getSession } from "@auth0/nextjs-auth0"
import { type JSX } from "react"
import { createOrUpdateUser, hasCompletedOnboarding } from "@codeflash-ai/common/user-functions"
import PostHogClient from "@/app/app/posthog"

// export const metadata: Metadata = {
//   title: 'Codeflash login',
//   description: 'The login page for Codeflash webapp'
// }

export default async function AuthenticationPage(): Promise<JSX.Element> {
  const session = await getSession()
  const user = session?.user

  if (user == null) {
    redirect("/api/auth/login")
  } else {
    console.log("user logged in!", user)
    if (!(user.sub && user.nickname)) {
      console.error("user.sub or user.nickname is null")
    } else {
      await createOrUpdateUser(user.sub, user.nickname, user.email ?? null, user.name ?? null)
      const posthog = PostHogClient()
      posthog.identify({
        distinctId: user.sub,
        properties: {
          username: user.nickname,
          email: user.email,
          name: session?.user?.name,
        },
      })
      posthog.capture({
        distinctId: user.sub,
        properties: { username: user.nickname,
        email: user.email },
        event: "webapp-user-logged-in",
      })
      await posthog.shutdown()
    }

    const completedOnboarding = await hasCompletedOnboarding(user.sub)
    if (!completedOnboarding) {
      console.log("user has not completed onboarding, redirecting")
      redirect("/onboarding")
      // redirect("https://vemx8ac1f86.typeform.com/to/GJhrpTZH")
    } else {
      console.log("user has completed onboarding, redirecting to /app")
      redirect("/app")
    }
  }
}
