"use server"

import {
  setUserReferralData,
  isUserReferralComplete,
  getUserReferralData,
} from "@codeflash-ai/common"
import PostHogClient from "@/lib/posthog"
import { auth0 } from "@/lib/auth0"

export async function upsertReferralSource(
  referralSource: string,
  additionalComments?: string,
): Promise<any> {
  const session = await auth0.getSession()
  if (session != null) {
    setUserReferralData(session.user.sub, referralSource, additionalComments)
    const posthog = PostHogClient()
    if (!posthog) return

    // Log the referral event to PostHog
    posthog.capture({
      distinctId: session.user.sub,
      event: "how-did-user-hear-about-codeflash",
      properties: {
        username: session.user.nickname,
        email: session.user.email,
        referral_source: referralSource,
        comments: additionalComments ?? null,
      },
    })
  }
}

export async function isReferralCompleted(userId: string) {
  return isUserReferralComplete(userId)
}

export async function getUserSelectedReferral(userId: string) {
  return getUserReferralData(userId)
}
