import type { APIRoute } from 'astro';
import { trendingAnalyticsService } from '../../../lib/analytics';
import { supabase } from '../../../lib/supabase';

export const POST: APIRoute = async ({ request }) => {
  try {
    const body = await request.json();
    const { eventId, metricType, sessionId, userId, locationData, metadata } = body;
    
    if (!eventId || !metricType) {
      return new Response(JSON.stringify({
        success: false,
        error: 'eventId and metricType are required'
      }), {
        status: 400,
        headers: {
          'Content-Type': 'application/json'
        }
      });
    }
    
    // Get client information
    const clientIP = request.headers.get('x-forwarded-for') || 
                    request.headers.get('x-real-ip') || 
                    'unknown';
    const userAgent = request.headers.get('user-agent') || 'unknown';
    const referrer = request.headers.get('referer') || undefined;
    
    // Track the event
    await trendingAnalyticsService.trackEvent({
      eventId,
      metricType,
      sessionId,
      userId,
      ipAddress: clientIP,
      userAgent,
      referrer,
      locationData,
      metadata
    });
    
    // Update popularity score if this is a significant event
    if (metricType === 'page_view' || metricType === 'checkout_complete') {
      // Don't await this to avoid slowing down the response
      trendingAnalyticsService.updateEventPopularityScore(eventId);
    }
    
    return new Response(JSON.stringify({
      success: true,
      message: 'Event tracked successfully'
    }), {
      status: 200,
      headers: {
        'Content-Type': 'application/json'
      }
    });
  } catch (error) {
    // Log error for debugging
    console.error('Failed to track analytics event:', error);
    return new Response(JSON.stringify({
      success: false,
      error: 'Failed to track event'
    }), {
      status: 500,
      headers: {
        'Content-Type': 'application/json'
      }
    });
  }
};