export const prerender = false;

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

export const POST: APIRoute = async ({ request }) => {
  try {
    const body = await request.json();
    const { 
      purchase_attempt_id, 
      payment_intent_id, 
      session_id 
    } = body;

    if (!purchase_attempt_id || !payment_intent_id || !session_id) {
      return new Response(JSON.stringify({ 
        error: 'purchase_attempt_id, payment_intent_id, and session_id are required' 
      }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Start a transaction to complete the purchase
    const { data: purchaseAttempt, error: purchaseError } = await supabase
      .from('purchase_attempts')
      .select(`
        *,
        purchase_attempt_items (
          *,
          ticket_types (
            event_id,
            name,
            price
          )
        )
      `)
      .eq('id', purchase_attempt_id)
      .eq('session_id', session_id)
      .eq('status', 'pending')
      .single();

    if (purchaseError || !purchaseAttempt) {
      return new Response(JSON.stringify({ 
        error: 'Purchase attempt not found or already processed' 
      }), {
        status: 404,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Update purchase attempt to completed
    const { error: updateError } = await supabase
      .from('purchase_attempts')
      .update({ 
        status: 'completed',
        stripe_payment_intent_id: payment_intent_id,
        completed_at: new Date().toISOString()
      })
      .eq('id', purchase_attempt_id);

    if (updateError) {
      throw updateError;
    }

    // Create actual tickets for each purchase item
    const ticketsToCreate = [];
    for (const item of purchaseAttempt.purchase_attempt_items) {
      for (let i = 0; i < item.quantity; i++) {
        ticketsToCreate.push({
          event_id: item.ticket_types.event_id,
          ticket_type_id: item.ticket_type_id,
          seat_id: item.seat_id,
          purchaser_email: purchaseAttempt.purchaser_email,
          purchaser_name: purchaseAttempt.purchaser_name,
          price: item.unit_price * 100, // Convert back to cents
          purchase_session_id: session_id,
          purchase_attempt_id: purchase_attempt_id,
          uuid: crypto.randomUUID() // Generate QR code UUID
        });
      }
    }

    const { data: createdTickets, error: ticketsError } = await supabase
      .from('tickets')
      .insert(ticketsToCreate)
      .select();

    if (ticketsError) {
      // Rollback purchase attempt
      await supabase
        .from('purchase_attempts')
        .update({ status: 'failed', failure_reason: 'Failed to create tickets' })
        .eq('id', purchase_attempt_id);
      
      throw ticketsError;
    }

    // Mark reservations as converted
    const { error: reservationsError } = await supabase
      .from('ticket_reservations')
      .update({ status: 'converted' })
      .eq('reserved_for_purchase_id', purchase_attempt_id);

    if (reservationsError) {
      console.error('Error updating reservations:', reservationsError);
      // Don't fail the entire purchase for this
    }

    // Release any reserved seats that are now taken
    for (const item of purchaseAttempt.purchase_attempt_items) {
      if (item.seat_id) {
        await supabase
          .from('seats')
          .update({ 
            is_available: false, 
            reserved_until: null,
            last_reserved_by: null 
          })
          .eq('id', item.seat_id);
      }
    }

    return new Response(JSON.stringify({
      success: true,
      purchase: {
        id: purchaseAttempt.id,
        total_amount: purchaseAttempt.total_amount,
        tickets_created: createdTickets.length,
        tickets: createdTickets.map(ticket => ({
          id: ticket.id,
          uuid: ticket.uuid,
          ticket_type_id: ticket.ticket_type_id
        }))
      }
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    console.error('Error completing purchase:', error);
    return new Response(JSON.stringify({ 
      error: 'Failed to complete purchase',
      details: error.message 
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};