/**
 * PostHog Server-Side Analytics Client
 * 
 * Uses posthog-node for trusted backend tracking:
 * - Server actions, Paystack webhooks, payment fulfillment
 * - Admin KYC approvals and moderation events
 * - Flush and shutdown safety for serverless and Node runtimes
 */

import { PostHog } from "posthog-node";
import {
  ANALYTICS_EVENTS,
  sanitizeTraits,
  PropertyCreatedProps,
  PropertySubmittedProps,
  PropertyPublishedProps,
  VerificationApprovedProps,
  VerificationNeedsActionProps,
  PaymentSuccessfulProps,
  PaymentFailedProps,
  UserTraits,
} from "./events";

let serverPostHogInstance: PostHog | null = null;

export function getServerPostHog(): PostHog | null {
  if (serverPostHogInstance) {
    return serverPostHogInstance;
  }

  const apiKey =
    process.env.POSTHOG_PROJECT_API_KEY || process.env.NEXT_PUBLIC_POSTHOG_KEY;
  const host =
    process.env.NEXT_PUBLIC_POSTHOG_HOST || "https://us.i.posthog.com";

  if (!apiKey) {
    return null;
  }

  try {
    serverPostHogInstance = new PostHog(apiKey, {
      host,
      flushAt: 1, // Flush immediately in serverless environments
      flushInterval: 0,
    });

    return serverPostHogInstance;
  } catch (err) {
    console.warn("[PostHog Server Client Init Warning]:", err);
    return null;
  }
}

/**
 * Capture a server-side analytics event with sanitized properties
 */
export async function captureServerEvent(
  distinctId: string,
  event: string,
  properties?: Record<string, any>
): Promise<void> {
  const client = getServerPostHog();
  if (!client || !distinctId) return;

  try {
    const cleanProperties = sanitizeTraits({
      ...properties,
      $lib: "posthog-node",
      environment: process.env.NODE_ENV,
    });

    client.capture({
      distinctId,
      event,
      properties: cleanProperties,
    });

    // In Next.js serverless functions, flush to ensure delivery before termination
    await client.flush();
  } catch (err) {
    // Analytics errors should NEVER crash user-facing requests or webhooks
    console.warn(`[PostHog Server Error] Failed to capture event "${event}":`, err);
  }
}

/**
 * Identify a user from the server with sanitized traits
 */
export async function identifyServerUser(
  distinctId: string,
  traits?: UserTraits
): Promise<void> {
  const client = getServerPostHog();
  if (!client || !distinctId) return;

  try {
    const cleanProperties = sanitizeTraits(traits);
    client.identify({
      distinctId,
      properties: cleanProperties,
    });
    await client.flush();
  } catch (err) {
    console.warn("[PostHog Server Error] Failed to identify user:", err);
  }
}

/**
 * Gracefully shuts down the PostHog node client instance
 */
export async function shutdownServerAnalytics(): Promise<void> {
  if (serverPostHogInstance) {
    try {
      await serverPostHogInstance.shutdown();
      serverPostHogInstance = null;
    } catch (err) {
      console.warn("[PostHog Server Shutdown Error]:", err);
    }
  }
}

/**
 * Semantic Server-Side Analytics Facade
 */
export const serverAnalytics = {
  identify: identifyServerUser,
  capture: captureServerEvent,

  trackPropertyCreated: (props: PropertyCreatedProps, distinctId: string) =>
    captureServerEvent(distinctId, ANALYTICS_EVENTS.PROPERTY_CREATED, props),

  trackPropertySubmitted: (props: PropertySubmittedProps, distinctId: string) =>
    captureServerEvent(distinctId, ANALYTICS_EVENTS.PROPERTY_SUBMITTED, props),

  trackPropertyPublished: (props: PropertyPublishedProps, distinctId: string) =>
    captureServerEvent(distinctId, ANALYTICS_EVENTS.PROPERTY_PUBLISHED, props),

  trackVerificationApproved: (props: VerificationApprovedProps, distinctId?: string) =>
    captureServerEvent(distinctId || props.user_id || "system", ANALYTICS_EVENTS.VERIFICATION_APPROVED, props),

  trackVerificationNeedsAction: (props: VerificationNeedsActionProps, distinctId?: string) =>
    captureServerEvent(distinctId || props.user_id || "system", ANALYTICS_EVENTS.VERIFICATION_NEEDS_ACTION, props),

  trackPaymentSuccess: (props: PaymentSuccessfulProps, distinctId?: string) =>
    captureServerEvent(distinctId || props.reference, ANALYTICS_EVENTS.PAYMENT_SUCCESSFUL, props),

  trackPaymentFailed: (props: PaymentFailedProps, distinctId?: string) =>
    captureServerEvent(distinctId || props.reference, ANALYTICS_EVENTS.PAYMENT_FAILED, props),
};

export default serverAnalytics;
