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

export const GET: APIRoute = async ({ request, url }) => {
  try {
    const searchParams = new URL(request.url).searchParams;
    
    // Get location parameters
    const latitude = searchParams.get('lat') ? parseFloat(searchParams.get('lat')!) : undefined;
    const longitude = searchParams.get('lng') ? parseFloat(searchParams.get('lng')!) : undefined;
    const radiusMiles = parseInt(searchParams.get('radius') || '50');
    const limit = parseInt(searchParams.get('limit') || '20');
    
    // Get user location from IP if not provided
    let userLat = latitude;
    let userLng = longitude;
    
    if (!userLat || !userLng) {
      const ipLocation = await geolocationService.getLocationFromIP();
      if (ipLocation) {
        userLat = ipLocation.latitude;
        userLng = ipLocation.longitude;
      }
    }
    
    // Get trending events
    const trendingEvents = await trendingAnalyticsService.getTrendingEvents(
      userLat,
      userLng,
      radiusMiles,
      limit
    );
    
    return new Response(JSON.stringify({
      success: true,
      data: trendingEvents,
      meta: {
        userLocation: userLat && userLng ? {
          latitude: userLat,
          longitude: userLng,
          radius: radiusMiles
        } : null,
        count: trendingEvents.length,
        limit
      }
    }), {
      status: 200,
      headers: {
        'Content-Type': 'application/json',
        'Cache-Control': 'public, max-age=300' // 5 minutes
      }
    });
  } catch (error) {

    return new Response(JSON.stringify({
      success: false,
      error: 'Failed to fetch trending events'
    }), {
      status: 500,
      headers: {
        'Content-Type': 'application/json'
      }
    });
  }
};