/**
 * Analytics Queue Helper
 *
 * Provides a simple interface for queueing analytics events
 * with automatic batching and deduplication.
 *
 * Replaces synchronous analytics calls with async jobs.
 */

import { enqueueAnalytics } from './bullmq';
import type { AnalyticsJobPayload } from './bullmq';
import { logger } from '@/lib/logger';
import { redisConfigured } from '@/lib/redis';

export interface QueuedAnalyticsOptions {
  event: string;
  userId?: string;
  sessionId?: string;
  properties?: Record<string, unknown>;
  timestamp?: string;
  /** Delay before processing (ms) */
  delayMs?: number;
  /** Deduplicate by event+userId (default: false) */
  deduplicate?: boolean;
}

/**
 * Queue an analytics event for background processing
 *
 * @example
 * await queueAnalyticsEvent({
 *   event: 'page_view',
 *   userId: 'user_123',
 *   sessionId: 'session_abc',
 *   properties: { page: '/pricing', referrer: '/home' },
 * });
 */
export async function queueAnalyticsEvent(
  options: QueuedAnalyticsOptions
): Promise<string> {
  const useQueue = process.env.ANALYTICS_QUEUE_ENABLED !== 'false' && redisConfigured;

  if (!useQueue) {
    logger.debug('Analytics queue disabled, event not tracked', {
      event: options.event,
      userId: options.userId,
    });
    return 'skipped-queue-disabled';
  }

  // Generate job ID for deduplication
  const jobId = options.deduplicate
    ? `analytics:${options.event}:${options.userId || 'anon'}:${Date.now()}`
    : undefined;

  const payload: AnalyticsJobPayload = {
    event: options.event,
    userId: options.userId,
    sessionId: options.sessionId,
    properties: options.properties,
    timestamp: options.timestamp || new Date().toISOString(),
  };

  const queuedJobId = await enqueueAnalytics(payload, {
    delay: options.delayMs,
    priority: 1, // Low priority
    attempts: 3, // Fewer retries for analytics
    jobId,
  });

  logger.debug('Analytics event queued (BullMQ)', {
    jobId: queuedJobId,
    event: options.event,
    userId: options.userId,
  });

  return queuedJobId;
}

/**
 * Track a page view event
 */
export async function trackPageView(
  userId: string | undefined,
  sessionId: string,
  page: string,
  referrer?: string
): Promise<string> {
  return queueAnalyticsEvent({
    event: 'page_view',
    userId,
    sessionId,
    properties: {
      page,
      referrer,
      timestamp: new Date().toISOString(),
    },
  });
}

/**
 * Track a button click event
 */
export async function trackButtonClick(
  userId: string | undefined,
  sessionId: string,
  buttonName: string,
  location: string
): Promise<string> {
  return queueAnalyticsEvent({
    event: 'button_click',
    userId,
    sessionId,
    properties: {
      buttonName,
      location,
    },
  });
}

/**
 * Track a form submission
 */
export async function trackFormSubmission(
  userId: string | undefined,
  sessionId: string,
  formName: string,
  success: boolean
): Promise<string> {
  return queueAnalyticsEvent({
    event: 'form_submission',
    userId,
    sessionId,
    properties: {
      formName,
      success,
    },
  });
}

/**
 * Track an API call for performance monitoring
 */
export async function trackAPICall(
  endpoint: string,
  method: string,
  statusCode: number,
  duration: number,
  userId?: string
): Promise<string> {
  return queueAnalyticsEvent({
    event: 'api_call',
    userId,
    properties: {
      endpoint,
      method,
      statusCode,
      duration,
    },
  });
}

/**
 * Track a conversion event (signup, demo booking, etc.)
 */
export async function trackConversion(
  userId: string,
  sessionId: string,
  conversionType: 'signup' | 'demo_booking' | 'trial_started' | 'subscription_created',
  value?: number
): Promise<string> {
  return queueAnalyticsEvent({
    event: 'conversion',
    userId,
    sessionId,
    properties: {
      conversionType,
      value,
    },
  });
}
