import type { APIRoute } from 'astro';
import { createSupabaseServerClient } from '../../../lib/supabase-ssr';
import { createSupabaseAdmin } from '../../../lib/supabase-admin';

export const GET: APIRoute = async ({ request, cookies }) => {
  try {
    // Check authentication
    const supabase = createSupabaseServerClient(cookies);
    const { data: { session }, error: sessionError } = await supabase.auth.getSession();
    
    if (sessionError || !session) {
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Authentication required' 
      }), { 
        status: 401,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Use admin client to bypass RLS
    const serviceClient = createSupabaseAdmin();
    
    // Get events with organization and user details
    const { data: events, error } = await serviceClient
      .from('events')
      .select(`
        *,
        organizations(name),
        users!events_created_by_fkey(name, email)
      `)
      .order('created_at', { ascending: false });

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

    // Get ticket type counts for each event
    if (events) {
      for (const event of events) {
        const { data: ticketTypes } = await serviceClient
          .from('ticket_types')
          .select('id')
          .eq('event_id', event.id);
        event.ticket_type_count = ticketTypes ? ticketTypes.length : 0;
      }
    }

    return new Response(JSON.stringify({
      success: true,
      data: events || []
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    console.error('Admin events error:', error);
    return new Response(JSON.stringify({
      success: false,
      error: 'Failed to load events'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};