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

const connection = await pool.getConnection();

export async function POST(request: NextRequest) {


  const body = await request.text();
  const signature = (await headers()).get('stripe-signature');

  if (!signature) {
    return NextResponse.json({ error: 'Missing stripe signature' }, { status: 400 });
  }

  let event;

  try {
    event = stripe.webhooks.constructEvent(
      body,
      signature,
      process.env.STRIPE_WEBHOOK_SECRET!
    );
  } catch (error) {
    console.error('Webhook signature verification failed:', error);
    return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
  }

  try {
    switch (event.type) {
      case 'payment_intent.succeeded':
        await handlePaymentSuccess(event.data.object);
        break;
      
      case 'payment_intent.payment_failed':
        await handlePaymentFailure(event.data.object);
        break;
      
      case 'payment_intent.canceled':
        await handlePaymentCanceled(event.data.object);
        break;
      
      default:
        console.log(`Unhandled event type: ${event.type}`);
    }

    return NextResponse.json({ received: true });
  } catch (error) {
    console.error('Error processing webhook:', error);
    return NextResponse.json({ error: 'Webhook processing failed' }, { status: 500 });
  } finally {
    connection.release();
  }
}

async function handlePaymentSuccess(paymentIntent: any) {
  try {
    // Check if transaction already exists
    const existingTransactions: any = await connection.query(
      'SELECT id FROM transactions WHERE stripe_payment_intent_id = ?',
      [paymentIntent.id]
    );

    const transactionData = {
      amount: paymentIntent.amount / 100,
      currency: paymentIntent.currency,
      status: 'succeeded',
      stripe_payment_intent_id: paymentIntent.id,
      customer_email: paymentIntent.metadata.customerEmail,
      customer_name: paymentIntent.metadata.customerName,
      consultation_type: paymentIntent.metadata.consultationType,
      metadata: JSON.stringify(paymentIntent),
    };

    if (existingTransactions.length > 0) {
      // Update existing transaction
      await connection.query(
        `UPDATE transactions 
         SET amount = ?, currency = ?, status = ?, customer_email = ?, customer_name = ?, consultation_type = ?, metadata = ?, updated_at = CURRENT_TIMESTAMP 
         WHERE stripe_payment_intent_id = ?`,
        [
          transactionData.amount,
          transactionData.currency,
          transactionData.status,
          transactionData.customer_email,
          transactionData.customer_name,
          transactionData.consultation_type,
          transactionData.metadata,
          paymentIntent.id
        ]
      );
    } else {
      // Insert new transaction
      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,
          transactionData.amount,
          transactionData.currency,
          transactionData.status,
          transactionData.stripe_payment_intent_id,
          transactionData.customer_email,
          transactionData.customer_name,
          transactionData.consultation_type,
          transactionData.metadata
        ]
      );
    }

    console.log('Payment succeeded and stored:', paymentIntent.id);
    
    // Here you can also:
    // - Send confirmation email
    // - Update user credits
    // - Create consultation appointment
    // - Notify admin
    
  } catch (error) {
    console.error('Error handling payment success:', error);
    throw error;
  } finally {
    connection.release();
  }
}

async function handlePaymentFailure(paymentIntent: any) {
  try {
    await connection.query(
      `UPDATE transactions 
       SET status = ?, metadata = ?, updated_at = CURRENT_TIMESTAMP 
       WHERE stripe_payment_intent_id = ?`,
      [
        'failed',
        JSON.stringify(paymentIntent),
        paymentIntent.id
      ]
    );
    
    console.log('Payment failed updated in database:', paymentIntent.id);
  } catch (error) {
    console.error('Error handling payment failure:', error);
    throw error;
  } finally {
    connection.release();
  }
}

async function handlePaymentCanceled(paymentIntent: any) {
  try {
    await connection.query(
      `UPDATE transactions 
       SET status = ?, metadata = ?, updated_at = CURRENT_TIMESTAMP 
       WHERE stripe_payment_intent_id = ?`,
      [
        'canceled',
        JSON.stringify(paymentIntent),
        paymentIntent.id
      ]
    );
    
    console.log('Payment canceled updated in database:', paymentIntent.id);
  } catch (error) {
    console.error('Error handling payment canceled:', error);
    throw error;
  } finally {
    connection.release();
  }
}