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);
    
    console.log(`[API] Loading event stats for ${id}`);
    
    // First, verify the event exists and user has access
    const { data: event, error: eventError } = await supabase
      .from('events')
      .select('id, organization_id')
      .eq('id', id)
      .single();

    if (eventError || !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
    if (!auth.isAdmin && event.organization_id !== auth.organizationId) {
      return new Response(JSON.stringify({ 
        error: 'Access denied' 
      }), {
        status: 403,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Get ticket sales data - use simple query compatible with current schema
    console.log(`[API] Querying tickets for event_id: ${id}`);
    const { data: tickets, error: ticketsError } = await supabase
      .from('tickets')
      .select(`
        id,
        ticket_type_id,
        price,
        checked_in,
        scanned_at,
        created_at
      `)
      .eq('event_id', id);

    console.log(`[API] Tickets query result:`, { 
      tickets: tickets?.length || 0, 
      error: ticketsError?.message || 'none' 
    });

    if (ticketsError) {
      console.error('Error loading tickets:', ticketsError);
      return new Response(JSON.stringify({ 
        error: 'Failed to load ticket data',
        details: ticketsError.message
      }), {
        status: 500,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Get ticket types for availability calculation
    console.log(`[API] Querying ticket types for event_id: ${id}`);
    const { data: ticketTypes, error: ticketTypesError } = await supabase
      .from('ticket_types')
      .select('id, quantity_available, price, name')
      .eq('event_id', id);

    console.log(`[API] Ticket types query result:`, { 
      ticketTypes: ticketTypes?.length || 0, 
      error: ticketTypesError?.message || 'none' 
    });

    if (ticketTypesError) {
      console.error('Error loading ticket types:', ticketTypesError);
      return new Response(JSON.stringify({ 
        error: 'Failed to load ticket types',
        details: ticketTypesError.message
      }), {
        status: 500,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Calculate stats - filter by status = 'sold'
    const soldTickets = tickets?.filter(t => t.status === 'sold') || [];
    const checkedInTickets = tickets?.filter(t => t.checked_in || t.scanned_at) || [];
    
    // Calculate total revenue using ticket price (stored as decimal dollars, convert to cents)
    const totalRevenue = soldTickets.reduce((sum, ticket) => {
      // Price is stored as decimal dollars (e.g., "75.00"), convert to cents
      const priceInDollars = parseFloat(ticket.price) || 0;
      const priceInCents = Math.round(priceInDollars * 100);
      return sum + priceInCents;
    }, 0);

    const totalAvailable = ticketTypes?.reduce((sum, type) => sum + (type.quantity_available || 0), 0) || 0;
    const ticketsSold = soldTickets.length;
    const ticketsAvailable = totalAvailable - ticketsSold;

    // Platform fee (assuming 3% + $0.30 per ticket)
    const platformFees = soldTickets.length > 0 ? soldTickets.reduce((sum, _ticket, index) => {
      const feePerTicket = Math.round((totalRevenue * 0.03) / soldTickets.length) + 30; // 3% + $0.30 in cents
      return sum + feePerTicket;
    }, 0) : 0;

    const netRevenue = totalRevenue - platformFees;

    const stats = {
      totalRevenue,
      netRevenue,
      ticketsSold,
      ticketsAvailable,
      checkedIn: checkedInTickets.length
    };

    console.log(`[API] Event stats calculated:`, stats);

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