/**
 * Metadata Collection Utilities
 *
 * Automatic collection of context metadata for analytics events.
 */

import type { EventMetadata } from '../types';

/**
 * Collect browser metadata
 */
export function collectBrowserMetadata(): EventMetadata {
  if (typeof window === 'undefined') {
    return {};
  }

  const metadata: EventMetadata = {
    userAgent: navigator.userAgent,
    language: navigator.language,
    screenWidth: window.screen.width,
    screenHeight: window.screen.height,
    viewportWidth: window.innerWidth,
    viewportHeight: window.innerHeight,
    timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
    timestamp: new Date().toISOString(),
  };

  // UTM parameters
  const params = new URLSearchParams(window.location.search);
  const utmParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'];
  for (const param of utmParams) {
    const value = params.get(param);
    if (value) {
      metadata[param] = value;
    }
  }

  // Referrer
  if (document.referrer) {
    metadata.referrer = document.referrer;
  }

  return metadata;
}

/**
 * Collect server-side metadata
 */
export function collectServerMetadata(): EventMetadata {
  return {
    nodeVersion: process.version,
    platform: process.platform,
    timestamp: new Date().toISOString(),
  };
}
