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

export const prerender = false;

export const POST: APIRoute = async ({ request }) => {
  try {
    const body = await request.json();
    const { code, event_id, customer_email, customer_session } = body;

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

    // Validate presale code using database function
    const { data, error } = await supabase
      .rpc('validate_presale_code', {
        p_code: code,
        p_event_id: event_id,
        p_customer_email: customer_email || null,
        p_customer_session: customer_session || null
      });

    if (error) {
      throw error;
    }

    const result = data[0];

    if (!result.is_valid) {
      return new Response(JSON.stringify({ 
        success: false,
        error: result.error_message 
      }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Get accessible ticket types for this presale code
    const { data: accessibleTicketTypes, error: ticketTypesError } = await supabase
      .from('presale_code_ticket_types')
      .select(`
        ticket_type_id,
        ticket_types (
          id,
          name,
          description,
          price,
          presale_start_time,
          presale_end_time
        )
      `)
      .eq('presale_code_id', result.presale_code_id);

    return new Response(JSON.stringify({
      success: true,
      presale_code: {
        id: result.presale_code_id,
        discount_type: result.discount_type,
        discount_value: result.discount_value,
        uses_remaining: result.uses_remaining,
        customer_uses_remaining: result.customer_uses_remaining
      },
      accessible_ticket_types: accessibleTicketTypes?.map(att => att.ticket_types) || []
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    console.error('Error validating presale code:', error);
    return new Response(JSON.stringify({ 
      error: 'Failed to validate presale code',
      details: error.message 
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};