export const prerender = false;

import type { APIRoute } from 'astro';
import { getSupabaseAdmin } from '../../../lib/supabase-admin';
import { supabase } from '../../../lib/supabase';

export const POST: APIRoute = async ({ request }) => {
  try {
    // Get the authorization header
    const authHeader = request.headers.get('Authorization');
    if (!authHeader?.startsWith('Bearer ')) {

      return new Response(JSON.stringify({ error: 'No authorization token provided' }), {
        status: 401,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    const token = authHeader.split(' ')[1];
    
    // Verify the user
    const { data: { user }, error: authError } = await supabase.auth.getUser(token);
    if (authError || !user) {

      return new Response(JSON.stringify({ error: 'Invalid authorization token' }), {
        status: 401,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    const body = await request.json();
    const { eventId, cart, paymentMethod = 'cash', reservationIds = [] } = body;
    
    if (!eventId || !cart || !Array.isArray(cart) || cart.length === 0) {
      return new Response(JSON.stringify({ error: 'Event ID and cart items are required' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Get admin client
    const supabaseAdmin = getSupabaseAdmin();
    
    // Verify event exists and get organization
    const { data: event, error: eventError } = await supabaseAdmin
      .from('events')
      .select('id, title, organization_id')
      .eq('id', eventId)
      .single();

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

    // Verify reservations exist and are valid
    if (reservationIds.length > 0) {
      const { data: reservations, error: reservationError } = await supabaseAdmin
        .from('ticket_reservations')
        .select('id, ticket_type_id, quantity, expires_at, status')
        .in('id', reservationIds)
        .eq('status', 'active');

      if (reservationError || !reservations || reservations.length !== reservationIds.length) {
        return new Response(JSON.stringify({ error: 'Invalid or expired reservations' }), {
          status: 400,
          headers: { 'Content-Type': 'application/json' }
        });
      }

      // Check if reservations are still valid
      const now = new Date().toISOString();
      for (const reservation of reservations) {
        if (reservation.expires_at < now) {
          return new Response(JSON.stringify({ error: 'One or more reservations have expired' }), {
            status: 400,
            headers: { 'Content-Type': 'application/json' }
          });
        }
      }
    }

    // Verify all ticket types exist and calculate total
    const ticketTypeIds = cart.map(item => item.ticketTypeId);
    const { data: ticketTypes, error: ticketTypesError } = await supabaseAdmin
      .from('ticket_types')
      .select('id, name, price, quantity_available, quantity_sold')
      .in('id', ticketTypeIds);

    if (ticketTypesError || !ticketTypes || ticketTypes.length !== ticketTypeIds.length) {
      return new Response(JSON.stringify({ error: 'Invalid ticket types' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Calculate total and prepare purchase details
    let totalAmount = 0;
    const purchaseDetails = [];

    for (const cartItem of cart) {
      const ticketType = ticketTypes.find(t => t.id === cartItem.ticketTypeId);
      if (!ticketType) {
        return new Response(JSON.stringify({ error: `Ticket type ${cartItem.ticketTypeId} not found` }), {
          status: 400,
          headers: { 'Content-Type': 'application/json' }
        });
      }

      totalAmount += ticketType.price * cartItem.quantity;
      purchaseDetails.push({
        ticketTypeId: ticketType.id,
        ticketTypeName: ticketType.name,
        quantity: cartItem.quantity,
        price: ticketType.price,
        subtotal: ticketType.price * cartItem.quantity
      });
    }

    // Create batch number for this purchase
    const batchNumber = `KIOSK-${Date.now()}-${Math.random().toString(36).substr(2, 6).toUpperCase()}`;

    // Create actual ticket entries in the tickets table
    const ticketsToCreate = [];
    
    for (const cartItem of cart) {
      const ticketType = ticketTypes.find(t => t.id === cartItem.ticketTypeId);
      
      for (let i = 0; i < cartItem.quantity; i++) {
        // Generate unique UUID for each ticket
        const ticketUuid = `${Date.now()}-${Math.random().toString(36).substr(2, 12).toUpperCase()}`;
        
        ticketsToCreate.push({
          event_id: eventId,
          ticket_type_id: cartItem.ticketTypeId,
          uuid: ticketUuid,
          price: ticketType.price,
          purchaser_email: 'kiosk@blackcanyontickets.com', // Placeholder for kiosk sales
          purchaser_name: `Kiosk Sale - ${batchNumber}`,
          checked_in: false,
          group_purchase_id: null, // Could use batch number UUID if needed
          refund_status: null
        });
      }
    }

    // Insert tickets into the main tickets table
    const { data: createdTickets, error: ticketError } = await supabaseAdmin
      .from('tickets')
      .insert(ticketsToCreate)
      .select();

    if (ticketError) {

      return new Response(JSON.stringify({ error: 'Failed to create tickets' }), {
        status: 500,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Update sold counts for ticket types
    const updatePromises = cart.map(async (cartItem) => {
      const ticketType = ticketTypes.find(t => t.id === cartItem.ticketTypeId);
      const newSoldCount = (ticketType.quantity_sold || 0) + cartItem.quantity;
      
      return supabaseAdmin
        .from('ticket_types')
        .update({ quantity_sold: newSoldCount })
        .eq('id', cartItem.ticketTypeId);
    });

    await Promise.all(updatePromises);

    // Create payment-specific instructions
    const baseInstructions = [
      `Provide ${createdTickets.length} printed tickets from inventory`,
      `Update printed ticket status to 'distributed' in management system`,
      `Reference batch: ${batchNumber}`
    ];
    
    const paymentInstructions = paymentMethod === 'cash' 
      ? [`Collect cash payment: $${(totalAmount / 100).toFixed(2)}`, ...baseInstructions]
      : [`Process credit card payment: $${(totalAmount / 100).toFixed(2)}`, ...baseInstructions];

    // Return success response with ticket details
    return new Response(JSON.stringify({
      success: true,
      purchase: {
        batchNumber,
        totalAmount,
        paymentMethod,
        purchaseDetails,
        ticketsCreated: createdTickets,
        ticketsNeeded: createdTickets.length,
        instructions: paymentInstructions
      }
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });

  } catch (error) {

    return new Response(JSON.stringify({ 
      error: 'Internal server error',
      details: error instanceof Error ? error.message : 'Unknown error'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};