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 tickets with event and organization details
    const { data: tickets, error } = await serviceClient
      .from('tickets')
      .select(`
        *,
        ticket_types (
          name,
          price
        ),
        events (
          title,
          venue,
          start_time,
          organizations (
            name
          )
        )
      `)
      .order('created_at', { ascending: false })
      .limit(100);

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

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