import { NextResponse } from 'next/server';
import { db, PaymentRecord, SubscriptionRecord } from '@/lib/db';
import { FlutterwaveGateway } from '@/lib/gateways/flutterwave';

export async function POST(req: Request) {
    try {
        const payload = await req.json();
        console.log("Flutterwave Webhook Payload:", JSON.stringify(payload, null, 2));

        const data = payload.data;
        if (!data || !data.id) {
            return NextResponse.json({ error: 'Invalid payload' }, { status: 400 });
        }

        // Auto-detection: Instead of checking a pre-shared secret hash, 
        // we call the Flutterwave API to verify this transaction authoritatively.
        const settings = await db.getSettings();
        const gateway = new FlutterwaveGateway(settings);
        const verification = await gateway.verifyPayment(data.id.toString());

        if (verification.paid) {
            const txRef = verification.sessionId; // This is the tx_ref returned by FLW
            const transactionId = data.id.toString();
            
            const userId = verification.userId;
            const userEmail = verification.userEmail;
            const planId = verification.planId;

            if (userEmail && planId) {
                // Check idempotency: ensure payment isn't already processed
                // We use transactionId as the primary key for the payment record to avoid duplicate processing
                const payments = await db.getPayments(100);
                const existingPayment = payments.find(p => p.id === transactionId || p.id === txRef);

                if (existingPayment) {
                    console.log(`Flutterwave payment already processed for ID ${transactionId} or ref ${txRef}`);
                    return NextResponse.json({ message: 'Already processed' });
                }

                const plans = await db.getPlans();
                const plan = plans.find(p => p.id === planId);

                if (plan) {
                    // Save as new Payment
                    const payment: PaymentRecord = {
                        id: transactionId,
                        userId: userId,
                        userEmail: userEmail,
                        planId: planId,
                        amount: plan.price,
                        status: 'succeeded',
                        paymentGateway: 'flutterwave',
                        createdAt: new Date().toISOString()
                    };
                    await db.savePayment(payment);

                    // Credit tokens
                    await db.updateTokenBalance(
                        userEmail,
                        plan.tokens,
                        'add',
                        `Purchase: ${plan.name} (Flutterwave)`
                    );

                    // Save Subscription so AI Tools unlock
                    const subscription: SubscriptionRecord = {
                        id: transactionId,
                        userEmail: userEmail,
                        planId: planId,
                        status: 'active',
                        createdAt: new Date().toISOString()
                    };
                    await db.saveSubscription(subscription);

                    console.log(`[Flutterwave] Successfully credited ${plan.tokens} tokens to ${userEmail}`);
                } else {
                    console.error("[Flutterwave] Plan not found for ID:", planId);
                }
            } else {
                console.error("[Flutterwave] Missing metadata in webhook data:", data.meta);
            }
        }

        return NextResponse.json({ received: true });

    } catch (err: any) {
        console.error("Flutterwave Webhook processing error:", err);
        return NextResponse.json({ error: 'Webhook processing failed' }, { status: 500 });
    }
}
