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

export const GET: APIRoute = async ({ request, url }) => {
  try {
    const searchParams = new URL(request.url).searchParams;
    
    // Get required location parameters
    const latitude = searchParams.get('lat');
    const longitude = searchParams.get('lng');
    
    if (!latitude || !longitude) {
      return new Response(JSON.stringify({
        success: false,
        error: 'Latitude and longitude are required'
      }), {
        status: 400,
        headers: {
          'Content-Type': 'application/json'
        }
      });
    }
    
    const radiusMiles = parseInt(searchParams.get('radius') || '25');
    const limit = parseInt(searchParams.get('limit') || '10');
    
    // Get hot events in the area
    const nearbyEvents = await trendingAnalyticsService.getHotEventsInArea(
      parseFloat(latitude),
      parseFloat(longitude),
      radiusMiles,
      limit
    );
    
    return new Response(JSON.stringify({
      success: true,
      data: nearbyEvents,
      meta: {
        userLocation: {
          latitude: parseFloat(latitude),
          longitude: parseFloat(longitude),
          radius: radiusMiles
        },
        count: nearbyEvents.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 nearby events'
    }), {
      status: 500,
      headers: {
        'Content-Type': 'application/json'
      }
    });
  }
};