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(),
      },
    })

    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)
  }
}

// --- New tracking events for key user journeys ---

/**
 * Captures a single event and flushes. All tracking helpers funnel through this
 * so we have one place to handle errors / shutdown.
 */
function captureEvent(distinctId: string, event: string, properties?: Record<string, unknown>) {
  try {
    const posthog = getPostHogClient()
    if (!posthog) return

    posthog.capture({
      distinctId,
      event,
      properties: {
        ...properties,
        timestamp: new Date().toISOString(),
      },
    })
  } catch (error) {
    // Never let tracking errors break the calling flow
    console.error(`[Analytics] Failed to track ${event}:`, error)
  }
}

export function trackOptimizationReviewed(
  userId: string,
  properties: {
    traceId: string
    functionName?: string | null
    repositoryName?: string | null
    status?: string | null
  },
) {
  captureEvent(userId, "optimization_reviewed", properties)
}

export function trackRepositoryConnected(
  userId: string,
  properties: {
    repositoryId: string
    repositoryName: string
  },
) {
  captureEvent(userId, "repository_connected", properties)
}

export function trackApiKeyCreated(
  userId: string,
  properties: {
    keyName: string
    organizationId?: string
  },
) {
  captureEvent(userId, "api_key_created", properties)
}

export function trackMemberInvited(
  userId: string,
  properties: {
    invitedUsername: string
    role: string
    scope: "organization" | "repository"
    targetId: string
  },
) {
  captureEvent(userId, "member_invited", properties)
}

export function trackBillingPageViewed(
  userId: string,
  properties?: {
    username?: string
  },
) {
  captureEvent(userId, "billing_page_viewed", properties)
}
