import { NextRequest, NextResponse } from 'next/server';
import { stripe } from '../../../../lib/stripe';
import pool from '../../../../lib/db/db';

export async function POST(request: NextRequest) {
    
    const connection = await pool.getConnection();

  try {
    const { amount, consultationType, customerEmail, customerName } = await request.json();

    // Validate amount
    if (amount < 0.5) {
      return NextResponse.json(
        { error: 'Amount must be at least $0.50' },
        { status: 400 }
      );
    }

    // Create Payment Intent
    const paymentIntent = await stripe.paymentIntents.create({
      amount: Math.round(amount * 100), // Convert to cents
      currency: 'pkr',
      metadata: {
        consultationType,
        customerName,
        customerEmail,
      },
      automatic_payment_methods: {
        enabled: true,
      },
    });

    // Create initial transaction record with pending status
    const transactionId = `txn_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    
    await connection.query(
      `INSERT INTO transactions (id, amount, currency, status, stripe_payment_intent_id, customer_email, customer_name, consultation_type, metadata) 
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        transactionId,
        amount,
        'pkr',
        'pending',
        paymentIntent.id,
        customerEmail,
        customerName,
        consultationType,
        JSON.stringify({
          stripe_payment_intent_id: paymentIntent.id,
          created_at: new Date().toISOString()
        })
      ]
    );

    return NextResponse.json({
      clientSecret: paymentIntent.client_secret,
      paymentIntentId: paymentIntent.id,
      transactionId: transactionId
    });
  } catch (error) {
    console.error('Error creating payment intent:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  } finally {
    connection.release();
  }
}