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

export const prerender = false;

export const GET: APIRoute = async ({ params }) => {
  const ticketTypeId = params.ticketTypeId;
  
  if (!ticketTypeId) {
    return new Response(JSON.stringify({ error: 'ticket_type_id is required' }), {
      status: 400,
      headers: { 'Content-Type': 'application/json' }
    });
  }

  try {
    // Get real-time availability using the database function
    const { data, error } = await supabase
      .rpc('get_ticket_availability', { p_ticket_type_id: ticketTypeId });

    if (error) {
      throw error;
    }

    const availability = data[0];

    return new Response(JSON.stringify({
      success: true,
      availability: {
        available: availability.available_quantity,
        total: availability.total_quantity,
        reserved: availability.reserved_quantity,
        sold: availability.sold_quantity,
        is_available: availability.available_quantity > 0
      }
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    // Log error for debugging
    console.error('Failed to get ticket availability:', error);
    return new Response(JSON.stringify({ 
      error: 'Failed to get availability',
      details: error instanceof Error ? error.message : 'Unknown error'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};