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

// 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 || '';

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

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 {
    if (!supabase) {
      return new Response(JSON.stringify({
        success: false,
        error: 'Database not available'
      }), {
        status: 500,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Get all events with organization info (admin view)
    const { data: events, error } = await supabase
      .from('events')
      .select(`
        id,
        title,
        description,
        venue,
        start_time,
        end_time,
        image_url,
        slug,
        category,
        is_featured,
        is_public,
        is_published,
        external_source,
        organization_id,
        created_at
      `)
      .order('created_at', { ascending: false });

    if (error) {
      return new Response(JSON.stringify({
        success: false,
        error: error.message
      }), {
        status: 500,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    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: events || [],
      total: events?.length || 0,
      summary: {
        total: events?.length || 0,
        featured: events?.filter(e => e.is_featured).length || 0,
        public: events?.filter(e => e.is_public).length || 0,
        firebase: events?.filter(e => e.external_source === 'firebase').length || 0,
        byOrganization: events?.reduce((acc: any, event) => {
          const orgId = event.organization_id || 'no-org';
          acc[orgId] = (acc[orgId] || 0) + 1;
          return acc;
        }, {}) || {}
      }
    }), {
      status: 200,
      headers: {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache'
      }
    });

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

    return new Response(JSON.stringify({
      success: false,
      error: 'Internal server error'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};