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

export const GET: APIRoute = async ({ url }) => {
  try {
    const eventId = url.searchParams.get('event_id');
    
    if (!eventId) {
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Event ID is required' 
      }), { status: 400 });
    }

    const { data: tickets, error } = await supabase
      .from('printed_tickets')
      .select(`
        *,
        ticket_types (
          name,
          price
        ),
        events (
          title
        )
      `)
      .eq('event_id', eventId)
      .order('created_at', { ascending: false });

    if (error) {
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Failed to fetch printed tickets' 
      }), { status: 500 });
    }

    return new Response(JSON.stringify({ 
      success: true, 
      tickets: tickets || []
    }), { status: 200 });

  } catch (error) {
    console.error('Fetch printed tickets error:', error);
    return new Response(JSON.stringify({ 
      success: false, 
      error: 'Internal server error' 
    }), { status: 500 });
  }
};

export const POST: APIRoute = async ({ request }) => {
  try {
    const { barcodes, event_id, ticket_type_id, batch_number, notes, issued_by } = await request.json();

    if (!barcodes || !Array.isArray(barcodes) || barcodes.length === 0) {
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Barcodes array is required' 
      }), { status: 400 });
    }

    if (!event_id || !ticket_type_id) {
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Event ID and ticket type ID are required' 
      }), { status: 400 });
    }

    // Prepare tickets for insertion
    const ticketsToInsert = barcodes.map(barcode => ({
      barcode_number: barcode.trim(),
      event_id,
      ticket_type_id,
      batch_number: batch_number || null,
      notes: notes || null,
      issued_by: issued_by || null,
      status: 'valid'
    }));

    // Insert tickets
    const { data: insertedTickets, error: insertError } = await supabase
      .from('printed_tickets')
      .insert(ticketsToInsert)
      .select();

    if (insertError) {
      // Handle duplicate barcode error
      if (insertError.code === '23505') {
        return new Response(JSON.stringify({ 
          success: false, 
          error: 'One or more barcodes already exist' 
        }), { status: 409 });
      }
      
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Failed to insert printed tickets' 
      }), { status: 500 });
    }

    return new Response(JSON.stringify({ 
      success: true, 
      message: `Successfully added ${insertedTickets.length} printed tickets`,
      tickets: insertedTickets
    }), { status: 201 });

  } catch (error) {
    console.error('Add printed tickets error:', error);
    return new Response(JSON.stringify({ 
      success: false, 
      error: 'Internal server error' 
    }), { status: 500 });
  }
};

export const PUT: APIRoute = async ({ request }) => {
  try {
    const { id, status, notes } = await request.json();

    if (!id) {
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Ticket ID is required' 
      }), { status: 400 });
    }

    const updateData: any = {};
    if (status) updateData.status = status;
    if (notes !== undefined) updateData.notes = notes;

    const { error } = await supabase
      .from('printed_tickets')
      .update(updateData)
      .eq('id', id);

    if (error) {
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Failed to update printed ticket' 
      }), { status: 500 });
    }

    return new Response(JSON.stringify({ 
      success: true, 
      message: 'Printed ticket updated successfully'
    }), { status: 200 });

  } catch (error) {
    console.error('Update printed ticket error:', error);
    return new Response(JSON.stringify({ 
      success: false, 
      error: 'Internal server error' 
    }), { status: 500 });
  }
};