export const prerender = false;

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

export const POST: APIRoute = async ({ request }) => {
  try {
    // Server-side authentication check
    const auth = await verifyAuth(request);
    if (!auth) {
      return new Response(JSON.stringify({ error: 'Unauthorized' }), {
        status: 401,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    let body;
    try {
      body = await request.json();
    } catch (jsonError) {
      // Log JSON parsing error for debugging
      console.error('JSON parsing error:', jsonError);
      return new Response(JSON.stringify({ 
        error: 'Invalid JSON in request body',
        details: jsonError instanceof Error ? jsonError.message : 'Invalid JSON format'
      }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const { 
      ticket_type_id, 
      quantity, 
      session_id, 
      hold_minutes = 15, 
      seat_ids = null 
    } = body;

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

    // Reserve tickets using the database function
    const { data, error } = await supabase
      .rpc('reserve_tickets', {
        p_ticket_type_id: ticket_type_id,
        p_quantity: quantity,
        p_reserved_by: session_id,
        p_hold_minutes: hold_minutes,
        p_seat_ids: seat_ids
      });

    if (error) {
      throw error;
    }

    const reservationId = data;

    // Get the reservation details
    const { data: reservation, error: reservationError } = await supabase
      .from('ticket_reservations')
      .select('*')
      .eq('id', reservationId)
      .single();

    if (reservationError) {
      throw reservationError;
    }

    return new Response(JSON.stringify({
      success: true,
      reservation: {
        id: reservation.id,
        ticket_type_id: reservation.ticket_type_id,
        quantity: reservation.quantity,
        expires_at: reservation.expires_at,
        seat_id: reservation.seat_id,
        status: reservation.status
      }
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    // Log error for debugging
    console.error('Failed to reserve tickets:', error);
    // Check if it's an availability error
    if (error.message && error.message.includes('Insufficient tickets available')) {
      return new Response(JSON.stringify({ 
        error: 'Insufficient tickets available',
        details: error instanceof Error ? error.message : 'Unknown error'
      }), {
        status: 409, // Conflict
        headers: { 'Content-Type': 'application/json' }
      });
    }

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