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 platform statistics
    const [organizationsResult, eventsResult, ticketsResult, usersResult] = await Promise.all([
      serviceClient.from('organizations').select('id'),
      serviceClient.from('events').select('id'),
      serviceClient.from('tickets').select('price'),
      serviceClient.from('users').select('id')
    ]);

    const organizations = organizationsResult.data?.length || 0;
    const events = eventsResult.data?.length || 0;
    const tickets = ticketsResult.data || [];
    const users = usersResult.data?.length || 0;
    const ticketCount = tickets.length;
    const revenue = tickets.reduce((sum, ticket) => sum + (ticket.price || 0), 0);
    const platformFees = revenue * 0.05; // Assuming 5% platform fee

    return new Response(JSON.stringify({
      success: true,
      data: {
        organizations,
        events,
        tickets: ticketCount,
        revenue,
        platformFees,
        users
      }
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    console.error('Admin stats error:', error);
    return new Response(JSON.stringify({
      success: false,
      error: 'Failed to load platform statistics'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};