export const prerender = false;

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

export const POST: APIRoute = async ({ request }) => {
  try {
    let body;
    try {
      body = await request.json();
    } catch (jsonError) {
      console.error('JSON parsing error in release endpoint:', jsonError);
      return new Response(JSON.stringify({ 
        error: 'Invalid JSON in request body',
        details: jsonError.message
      }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    const { reservation_id, session_id } = body;

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

    // Cancel the reservation
    const { data, error } = await supabase
      .from('ticket_reservations')
      .update({ status: 'cancelled' })
      .eq('id', reservation_id)
      .eq('reserved_by', session_id)
      .eq('status', 'active')
      .select();

    if (error) {
      throw error;
    }

    if (data.length === 0) {
      return new Response(JSON.stringify({ 
        error: 'Reservation not found or not owned by this session' 
      }), {
        status: 404,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    const reservation = data[0];

    // Release any associated seats
    if (reservation.seat_id) {
      await supabase
        .from('seats')
        .update({ 
          is_available: true, 
          reserved_until: null, 
          last_reserved_by: null 
        })
        .eq('id', reservation.seat_id);
    }

    return new Response(JSON.stringify({
      success: true,
      message: 'Reservation cancelled and tickets released'
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    console.error('Error releasing reservation:', error);
    return new Response(JSON.stringify({ 
      error: 'Failed to release reservation',
      details: error.message 
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};