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

export const GET: APIRoute = async ({ cookies }) => {
  try {
    // Verify authentication using server-side auth
    const auth = await verifyAuth(cookies);
    
    if (!auth) {
      return new Response(JSON.stringify({ 
        error: 'Not authenticated' 
      }), {
        status: 401,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    // Create Supabase client for server-side queries
    const supabase = createSupabaseServerClient(cookies);
    
    // Get user profile to check if they're admin
    const { data: userProfile, error: profileError } = await supabase
      .from('users')
      .select('role, organization_id')
      .eq('id', auth.user.id)
      .single();

    if (profileError) {
      console.error('Error loading user profile:', profileError);
      return new Response(JSON.stringify({ 
        error: 'Error loading user profile' 
      }), {
        status: 500,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Check if user is admin or has organization_id
    const isAdmin = userProfile?.role === 'admin';
    if (!isAdmin && !userProfile?.organization_id) {
      return new Response(JSON.stringify({ 
        success: true,
        data: []
      }), {
        status: 200,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Load events based on user permissions
    let query = supabase.from('events').select('*');
    
    if (!isAdmin) {
      // Regular users see only their organization's events
      query = query.eq('organization_id', userProfile.organization_id);
    }
    // Admins see all events (no filter)
    
    const { data: events, error } = await query.order('created_at', { ascending: false });

    if (error) {
      console.error('Error loading events:', error);
      return new Response(JSON.stringify({ 
        error: 'Error loading events' 
      }), {
        status: 500,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    return new Response(JSON.stringify({
      success: true,
      data: events || []
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });

  } catch (error) {
    console.error('User events API error:', error);
    return new Response(JSON.stringify({ 
      error: 'Internal server error' 
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};