/**
 * Analytics Worker
 *
 * Processes analytics jobs from the BullMQ analytics queue.
 * Handles event tracking, metrics aggregation, and user behavior analysis.
 *
 * Features:
 * - Batch processing for efficiency
 * - Event validation
 * - Duplicate detection
 * - Rate limiting (200 events/minute)
 *
 * NOTE: Analytics events are logged. Database persistence was removed
 * as part of the Supabase-to-Convex migration. Future: route to Convex
 * analytics mutations if needed.
 */

import 'server-only';
import { Job } from 'bullmq';
import { registerWorker, QUEUE_NAMES, AnalyticsJobPayload } from '../bullmq';
import { logger } from '@/lib/logger';

/**
 * Analytics job processor
 */
async function processAnalyticsJob(job: Job<AnalyticsJobPayload>): Promise<void> {
  const { event, userId, sessionId, properties, timestamp } = job.data;

  logger.debug('[AnalyticsWorker] Processing analytics event', {
    jobId: job.id,
    event,
    userId,
    sessionId,
    attempt: job.attemptsMade + 1,
  });

  // Validate event payload
  if (!event) {
    throw new Error('Invalid analytics payload: missing event name');
  }

  // Log the analytics event (database write removed with Supabase)
  logger.info('[AnalyticsWorker] Analytics event recorded', {
    jobId: job.id,
    event,
    userId,
    sessionId,
    properties,
    timestamp: timestamp || new Date().toISOString(),
  });
}

/**
 * Start the analytics worker
 */
export function startAnalyticsWorker() {
  const worker = registerWorker<AnalyticsJobPayload>(
    QUEUE_NAMES.ANALYTICS,
    processAnalyticsJob,
    {
      concurrency: 20, // Process 20 events concurrently
      limiter: {
        max: 200, // Max 200 events
        duration: 60000, // Per minute
      },
    }
  );

  logger.info('[AnalyticsWorker] Started with concurrency=20, rate=200/min');

  return worker;
}
