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

export const GET: APIRoute = async ({ url, cookies }) => {
  try {
    // Get query parameters
    const eventId = url.searchParams.get('event_id');
    const ticketTypeId = url.searchParams.get('ticket_type_id');
    
    if (!eventId || !ticketTypeId) {
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Event ID and ticket type ID are required' 
      }), { status: 400 });
    }

    // Authenticate user (basic auth check)
    const token = cookies.get('sb-access-token')?.value;
    if (!token) {
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Authentication required' 
      }), { status: 401 });
    }

    // Fetch event and ticket type data
    const { data: eventData, error: eventError } = await supabase
      .from('events')
      .select(`
        id,
        title,
        description,
        start_time,
        end_time,
        venue,
        address,
        image_url,
        organizations (
          name
        )
      `)
      .eq('id', eventId)
      .single();

    if (eventError || !eventData) {
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Event not found' 
      }), { status: 404 });
    }

    const { data: ticketTypeData, error: ticketTypeError } = await supabase
      .from('ticket_types')
      .select('id, name, price, description')
      .eq('id', ticketTypeId)
      .eq('event_id', eventId)
      .single();

    if (ticketTypeError || !ticketTypeData) {
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Ticket type not found' 
      }), { status: 404 });
    }

    // Format dates
    const startTime = new Date(eventData.start_time);
    const eventDate = startTime.toLocaleDateString('en-US', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
    
    const eventTime = startTime.toLocaleTimeString('en-US', {
      hour: 'numeric',
      minute: '2-digit',
      hour12: true
    });

    // Prepare preview data
    const previewData = {
      eventTitle: eventData.title,
      eventDate: eventDate,
      eventTime: eventTime,
      venue: eventData.venue,
      address: eventData.address,
      ticketTypeName: ticketTypeData.name,
      ticketTypePrice: ticketTypeData.price,
      organizationName: eventData.organizations?.name || 'Event Organizer',
      imageUrl: eventData.image_url
    };

    return new Response(JSON.stringify({ 
      success: true, 
      preview: previewData
    }), { status: 200 });

  } catch (error) {
    // Log error for debugging
    console.error('Failed to generate ticket preview:', error);
    return new Response(JSON.stringify({ 
      success: false, 
      error: 'Internal server error' 
    }), { status: 500 });
  }
};