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 organizations
    const { data: orgs, error } = await serviceClient
      .from('organizations')
      .select('*')
      .order('created_at', { ascending: false });

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

    // Get user counts for each organization
    if (orgs) {
      for (const org of orgs) {
        const { data: users } = await serviceClient
          .from('users')
          .select('id')
          .eq('organization_id', org.id);
        org.user_count = users ? users.length : 0;
      }
    }

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