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

export const GET: APIRoute = async ({ params, cookies }) => {
  try {
    const { id } = params;
    
    if (!id) {
      return new Response(JSON.stringify({ 
        error: 'Event ID is required' 
      }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    // 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);
    
    // Load event data with seating map
    console.log(`[API] Loading event ${id} for user ${auth.user.id} (org: ${auth.organizationId})`);
    
    const { data: event, error } = await supabase
      .from('events')
      .select(`
        *,
        seating_maps (
          id,
          name,
          layout_data
        )
      `)
      .eq('id', id)
      .single();

    if (error) {
      console.error('Error loading event:', error);
      return new Response(JSON.stringify({ 
        error: 'Event not found',
        details: error.message 
      }), {
        status: 404,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    if (!event) {
      return new Response(JSON.stringify({ 
        error: 'Event not found' 
      }), {
        status: 404,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Check if user has access to this event
    console.log(`[API] Access check - User org: ${auth.organizationId}, Event org: ${event.organization_id}, Is admin: ${auth.isAdmin}`);
    
    // If not admin and event doesn't belong to user's organization, deny access
    if (!auth.isAdmin && event.organization_id !== auth.organizationId) {
      console.error(`[API] Access denied - Event org ${event.organization_id} != User org ${auth.organizationId}`);
      return new Response(JSON.stringify({ 
        error: 'Access denied - event belongs to different organization' 
      }), {
        status: 403,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Return event data with seating map
    const eventData = {
      ...event,
      seating_map: event.seating_maps
    };

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

export const PUT: APIRoute = async ({ params, cookies, request }) => {
  try {
    const { id } = params;
    
    if (!id) {
      return new Response(JSON.stringify({ 
        error: 'Event ID is required' 
      }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    // 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);
    
    // First, verify user has access to this event
    const { data: existingEvent, error: fetchError } = await supabase
      .from('events')
      .select('id, organization_id')
      .eq('id', id)
      .single();
    
    if (fetchError || !existingEvent) {
      return new Response(JSON.stringify({ 
        error: 'Event not found' 
      }), {
        status: 404,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    // Check if user has access to this event
    if (!auth.isAdmin && existingEvent.organization_id !== auth.organizationId) {
      return new Response(JSON.stringify({ 
        error: 'Access denied' 
      }), {
        status: 403,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    // Parse request body
    const updateData = await request.json();
    console.log('[API] Updating event with data:', updateData);
    
    // Validate required fields
    if (!updateData.title || !updateData.venue || !updateData.start_time) {
      return new Response(JSON.stringify({ 
        error: 'Missing required fields: title, venue, start_time' 
      }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    // Update the event
    const { data: updatedEvent, error: updateError } = await supabase
      .from('events')
      .update({
        title: updateData.title,
        venue: updateData.venue,
        start_time: updateData.start_time,
        description: updateData.description || null
      })
      .eq('id', id)
      .select()
      .single();
    
    if (updateError) {
      console.error('Error updating event:', updateError);
      return new Response(JSON.stringify({ 
        error: 'Failed to update event',
        details: updateError.message 
      }), {
        status: 500,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    console.log('[API] Event updated successfully:', updatedEvent.id);
    
    return new Response(JSON.stringify(updatedEvent), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
    
  } catch (error) {
    console.error('Event update API error:', error);
    return new Response(JSON.stringify({ 
      error: 'Internal server error' 
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};