/**
 * Analytics Routes
 * Track events and conversions for marketing analytics
 */

import express from 'express'
import { asyncHandler } from '../middleware/errorHandler.mjs'
import { respond } from '../utils/response.mjs'

const router = express.Router()

/**
 * POST /api/analytics/track
 * Track analytics events (page views, conversions, etc.)
 * 
 * Body:
 * {
 *   type: 'page_view' | 'signup' | 'trial_start' | 'purchase' | 'email_connected',
 *   userId?: string,
 *   tracking?: {
 *     utm_source?: string,
 *     utm_medium?: string,
 *     utm_campaign?: string,
 *     utm_term?: string,
 *     utm_content?: string,
 *   },
 *   metadata?: Record<string, any>,
 *   timestamp?: string,
 *   page?: string,
 *   referrer?: string,
 * }
 */
router.post('/track', asyncHandler(async (req, res) => {
  const {
    type,
    userId,
    tracking,
    metadata,
    timestamp,
    page,
    referrer,
  } = req.body

  // Log analytics event (in production, send to analytics service)
  if (process.env.NODE_ENV === 'development') {
    console.log('📊 Analytics Event:', {
      type,
      userId,
      tracking,
      metadata,
      timestamp,
      page,
      referrer,
    })
  }

  // TODO: Store in database for analytics dashboard
  // For now, just log to console
  // In production, you might want to:
  // - Store in database
  // - Send to Google Analytics / Plausible / etc.
  // - Send to Mixpanel / Amplitude
  // - Log to external analytics service

  // Return success (client doesn't need to wait)
  respond.success(res, { received: true })
}))

export default router
