import type { APIRoute } from 'astro';
import { createClient } from '@supabase/supabase-js';
import { logAPIRequest, logSecurityEvent } from '../../../lib/logger';
import { checkRateLimit } from '../../../lib/auth';

// Handle missing environment variables gracefully
const supabaseUrl = process.env.SUPABASE_URL || import.meta.env.SUPABASE_URL || 'https://zctjaivtfyfxokfaemek.supabase.co';
const supabaseServiceKey = process.env.SUPABASE_SERVICE_KEY || import.meta.env.SUPABASE_SERVICE_KEY || '';

// Create supabase client with fallback handling
let supabase: any = null;
try {
  if (supabaseUrl && supabaseServiceKey) {
    supabase = createClient(supabaseUrl, supabaseServiceKey);
  }
} catch (error) {
  // Silently handle Supabase initialization errors
}

interface PublicEvent {
  id: string;
  title: string;
  description: string;
  venue: string;
  start_time: string;
  end_time: string;
  image_url?: string;
  slug: string;
  ticket_url: string;
  organizer_name: string;
  category?: string;
  price_range?: string;
  is_featured: boolean;
}

export const GET: APIRoute = async ({ request, url }) => {
  const startTime = Date.now();
  const clientIP = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || 'unknown';
  const userAgent = request.headers.get('user-agent') || 'unknown';
  
  try {
    // Check if Supabase is available
    if (!supabase) {
      return new Response(JSON.stringify({
        success: true,
        events: [],
        total: 0,
        hasMore: false,
        message: 'Service temporarily unavailable'
      }), {
        status: 200,
        headers: {
          'Content-Type': 'application/json',
          'Cache-Control': 'public, max-age=60',
          'Access-Control-Allow-Origin': '*'
        }
      });
    }
    // Rate limiting - 100 requests per hour per IP
    if (!checkRateLimit(clientIP, 100, 3600000)) {
      logSecurityEvent({
        type: 'rate_limit',
        ipAddress: clientIP,
        userAgent,
        severity: 'medium',
        details: { endpoint: '/api/public/events', limit: 100 }
      });

      return new Response(JSON.stringify({ 
        error: 'Rate limit exceeded. Please try again later.' 
      }), {
        status: 429,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Parse query parameters
    const searchParams = url.searchParams;
    const limit = Math.min(parseInt(searchParams.get('limit') || '50'), 100); // Max 100 events
    const offset = parseInt(searchParams.get('offset') || '0');
    const category = searchParams.get('category');
    const search = searchParams.get('search');
    const featured = searchParams.get('featured') === 'true';
    const upcoming = searchParams.get('upcoming') !== 'false'; // Default to upcoming only

    // Build query
    let query = supabase
      .from('events')
      .select(`
        id,
        title,
        description,
        venue,
        start_time,
        end_time,
        image_url,
        slug,
        category,
        is_featured,
        organizations!inner(name)
      `)
      .eq('is_published', true)
      .eq('is_public', true) // Only show public events
      .order('start_time', { ascending: true });

    // Filter upcoming events
    if (upcoming) {
      query = query.gte('start_time', new Date().toISOString());
    }

    // Filter by category
    if (category) {
      query = query.eq('category', category);
    }

    // Filter featured events
    if (featured) {
      query = query.eq('is_featured', true);
    }

    // Search functionality
    if (search && search.trim()) {
      const searchTerm = search.trim();
      query = query.or(`title.ilike.%${searchTerm}%,description.ilike.%${searchTerm}%,venue.ilike.%${searchTerm}%`);
    }

    // Apply pagination
    query = query.range(offset, offset + limit - 1);

    const { data: events, error } = await query;

    if (error) {
      // Silently handle database errors
      return new Response(JSON.stringify({
        success: true,
        events: [],
        total: 0,
        hasMore: false,
        message: 'Unable to load events at this time'
      }), {
        status: 200,
        headers: { 
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        }
      });
    }

    // Transform data for public consumption
    const publicEvents: PublicEvent[] = events.map(event => {
      // Calculate price range from tickets (this would need a separate query in production)
      const priceRange = 'Free - $50'; // Placeholder - implement based on ticket prices
      
      return {
        id: event.id,
        title: event.title,
        description: event.description?.substring(0, 200) + (event.description?.length > 200 ? '...' : ''), // Truncate for security
        venue: event.venue,
        start_time: event.start_time,
        end_time: event.end_time,
        image_url: event.image_url,
        slug: event.slug,
        ticket_url: `${process.env.PUBLIC_APP_URL || import.meta.env.PUBLIC_APP_URL || 'http://localhost:4321'}/e/${event.slug}`,
        organizer_name: event.organizations?.name || 'Event Organizer',
        category: event.category,
        price_range: priceRange,
        is_featured: event.is_featured || false
      };
    });

    const responseTime = Date.now() - startTime;

    // Log API request
    logAPIRequest({
      method: 'GET',
      url: url.pathname + url.search,
      statusCode: 200,
      responseTime,
      ipAddress: clientIP,
      userAgent
    });

    return new Response(JSON.stringify({
      success: true,
      events: publicEvents,
      total: publicEvents.length,
      hasMore: publicEvents.length === limit,
      filters: {
        category,
        search,
        featured,
        upcoming
      }
    }), {
      status: 200,
      headers: {
        'Content-Type': 'application/json',
        'Cache-Control': 'public, max-age=300', // Cache for 5 minutes
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET',
        'Access-Control-Allow-Headers': 'Content-Type'
      }
    });

  } catch (error) {
    // Silently handle API errors
    const responseTime = Date.now() - startTime;
    
    logAPIRequest({
      method: 'GET',
      url: url.pathname + url.search,
      statusCode: 200,
      responseTime,
      ipAddress: clientIP,
      userAgent
    });

    return new Response(JSON.stringify({
      success: true,
      events: [],
      total: 0,
      hasMore: false,
      message: 'Service temporarily unavailable'
    }), {
      status: 200,
      headers: { 
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      }
    });
  }
};

// OPTIONS handler for CORS
export const OPTIONS: APIRoute = async () => {
  return new Response(null, {
    status: 200,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type',
      'Access-Control-Max-Age': '86400'
    }
  });
};