import PostHogClient from "../posthog"

function getPostHogClient() {
  return PostHogClient()
}

// Main tracking function for user login
export async function trackUserLogin(userData: {
  userId: string
  username: string
  email?: string
  name?: string
}) {
  try {
    const posthog = getPostHogClient()
    if (!posthog) return

    // Identify the user
    posthog.identify({
      distinctId: userData.userId,
      properties: {
        username: userData.username,
        email: userData.email,
        name: userData.name,
      },
    })

    // Track the login event
    posthog.capture({
      distinctId: userData.userId,
      event: "webapp-user-logged-in",
      properties: {
        username: userData.username,
        email: userData.email,
        timestamp: new Date().toISOString(),
      },
    })

    // Ensure events are sent
    await posthog?.shutdown()

    console.log(`[Analytics] Tracked login for user ${userData.userId}`)
  } catch (error) {
    // Don't let tracking errors break login
    console.error("[Analytics] Failed to track login:", error)
  }
}
