export const prerender = false;

import type { APIRoute } from 'astro';
import { stripe } from '../../../lib/stripe';
import { getSupabaseAdmin } from '../../../lib/supabase-admin';
import { supabase } from '../../../lib/supabase';

export const POST: APIRoute = async ({ request }) => {
  try {
    // Get the authorization header
    const authHeader = request.headers.get('Authorization');
    if (!authHeader?.startsWith('Bearer ')) {
      return new Response(JSON.stringify({ error: 'No authorization token provided' }), {
        status: 401,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    const token = authHeader.split(' ')[1];
    
    // Verify the user
    const { data: { user }, error: authError } = await supabase.auth.getUser(token);
    if (authError || !user) {
      return new Response(JSON.stringify({ error: 'Invalid authorization token' }), {
        status: 401,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    if (!stripe) {
      return new Response(JSON.stringify({ error: 'Payment processing not configured' }), {
        status: 500,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    const body = await request.json();
    const { amount, currency = 'usd', paymentMethodId, eventId, batchNumber } = body;
    
    if (!amount || !paymentMethodId || !eventId || !batchNumber) {
      return new Response(JSON.stringify({ error: 'Missing required payment information' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Get admin client
    const supabaseAdmin = getSupabaseAdmin();
    
    // Get event and organization details
    const { data: event, error: eventError } = await supabaseAdmin
      .from('events')
      .select(`
        id,
        title,
        organization_id,
        organizations (
          id,
          name,
          stripe_account_id
        )
      `)
      .eq('id', eventId)
      .single();

    if (eventError || !event) {
      return new Response(JSON.stringify({ error: 'Event not found' }), {
        status: 404,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Check if organization has Stripe Connect set up
    const stripeAccountId = event.organizations?.stripe_account_id;
    if (!stripeAccountId) {
      return new Response(JSON.stringify({ error: 'Payment processing not set up for this organization' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Create payment intent
    const paymentIntent = await stripe.paymentIntents.create({
      amount: Math.round(amount), // Amount in cents
      currency: currency,
      payment_method: paymentMethodId,
      confirmation_method: 'manual',
      confirm: true,
      return_url: `${import.meta.env.PUBLIC_APP_URL}/kiosk/payment-success`,
      application_fee_amount: Math.round(amount * 0.03), // 3% platform fee
      transfer_data: {
        destination: stripeAccountId,
      },
      metadata: {
        eventId,
        batchNumber,
        source: 'kiosk',
        organizationId: event.organization_id,
        eventTitle: event.title
      },
      description: `Kiosk sale - ${event.title} (Batch: ${batchNumber})`
    });

    // Handle payment result
    if (paymentIntent.status === 'succeeded') {
      return new Response(JSON.stringify({
        success: true,
        paymentIntent: {
          id: paymentIntent.id,
          status: paymentIntent.status,
          amount: paymentIntent.amount,
          currency: paymentIntent.currency
        }
      }), {
        status: 200,
        headers: { 'Content-Type': 'application/json' }
      });
    } else if (paymentIntent.status === 'requires_action') {
      // 3D Secure authentication required
      return new Response(JSON.stringify({
        requiresAction: true,
        paymentIntent: {
          id: paymentIntent.id,
          client_secret: paymentIntent.client_secret
        }
      }), {
        status: 200,
        headers: { 'Content-Type': 'application/json' }
      });
    } else {
      return new Response(JSON.stringify({
        error: 'Payment failed',
        status: paymentIntent.status
      }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

  } catch (error) {

    if (error.type === 'StripeCardError') {
      return new Response(JSON.stringify({
        error: 'Card declined',
        details: error.message
      }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    return new Response(JSON.stringify({ 
      error: 'Internal server error',
      details: error instanceof Error ? error.message : 'Unknown error'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};