import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import { retrievePaymentIntent, mapStripeStatusToPaymentStatus } from '@/lib/stripe';

interface ConfirmPaymentRequest {
  paymentIntentId: string;
}

export async function POST(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json(
        { 
          error: 'Authentication required',
          message: 'Your session has expired. Please log in again to confirm your payment.'
        },
        { status: 401 }
      );
    }

    const body: ConfirmPaymentRequest = await req.json();
    const { paymentIntentId } = body;

    if (!paymentIntentId) {
      return NextResponse.json(
        { 
          error: 'Invalid payment confirmation request',
          message: 'Payment confirmation data is missing. Please try the payment process again.'
        },
        { status: 400 }
      );
    }

    try {
      // Retrieve payment intent from Stripe
      const paymentIntent = await retrievePaymentIntent(paymentIntentId);

      // Verify this payment belongs to the current user (compare against database user id)
      if (paymentIntent.metadata?.userId !== session.user.id) {
        return NextResponse.json(
          { 
            error: 'Payment verification failed',
            message: 'This payment does not belong to your account. Please ensure you are logged in with the correct account.'
          },
          { status: 403 }
        );
      }

      // Map Stripe status
      const paymentStatus = mapStripeStatusToPaymentStatus(paymentIntent.status);

      // If payment succeeded and webhook hasn't processed it yet, process it now
      if (paymentIntent.status === 'succeeded' && paymentStatus === 'COMPLETED') {
        const categoryIds = paymentIntent.metadata?.categoryIds?.split(',') || [];
        
        // Debug logging
        console.log('[Payment Confirm] Session user ID:', session.user.id);
        console.log('[Payment Confirm] Session user email:', session.user.email);
        console.log('[Payment Confirm] Stripe metadata userId:', paymentIntent.metadata?.userId);
        
        // Verify user exists in database - try by ID first, then by email
        let existingUser = await prisma.user.findUnique({
          where: { id: session.user.id }
        });
        
        if (!existingUser && session.user.email) {
          console.log('[Payment Confirm] User not found by ID, trying by email...');
          existingUser = await prisma.user.findUnique({
            where: { email: session.user.email }
          });
        }
        
        if (!existingUser) {
          console.error('[Payment Confirm] User not found in database by ID or email:', session.user.id, session.user.email);
          return NextResponse.json(
            { 
              error: 'User verification failed',
              message: 'Your account could not be verified. Please try logging out and logging back in.'
            },
            { status: 400 }
          );
        }
        
        console.log('[Payment Confirm] User verified:', existingUser.id, existingUser.email);
        
        // Use the verified user ID for all database operations
        const verifiedUserId = existingUser.id;
        
        if (categoryIds.length > 0) {
          const currentDate = new Date();
          const expirationDate = new Date(currentDate.getTime() + 30 * 24 * 60 * 60 * 1000); // 30 days

          // Activate subscriptions
          for (const categoryId of categoryIds) {
            try {
              console.log(`[Payment Confirm] Processing subscription for category: ${categoryId}, user: ${verifiedUserId}`);
              
              const existingSubscription = await prisma.categorySubscription.findFirst({
                where: {
                  userId: verifiedUserId,
                  categoryId,
                },
              });

              if (existingSubscription) {
                console.log(`[Payment Confirm] Updating existing subscription: ${existingSubscription.id}`);
                await prisma.categorySubscription.update({
                  where: { id: existingSubscription.id },
                  data: {
                    status: 'ACTIVE',
                    endDate: expirationDate,
                    updatedAt: currentDate,
                  },
                });
                console.log(`[Payment Confirm] Successfully updated subscription: ${existingSubscription.id}`);
              } else {
                console.log(`[Payment Confirm] Creating new subscription for category: ${categoryId}`);
                const newSubscription = await prisma.categorySubscription.create({
                  data: {
                    userId: verifiedUserId,
                    categoryId,
                    status: 'ACTIVE',
                    startDate: currentDate,
                    endDate: expirationDate,
                  },
                });
                console.log(`[Payment Confirm] Successfully created subscription: ${newSubscription.id}`);
              }
            } catch (subscriptionError: any) {
              console.error('[Payment Confirm] Error activating subscription for category:', categoryId);
              console.error('[Payment Confirm] Error details:', {
                error: subscriptionError.message,
                code: subscriptionError.code,
                meta: subscriptionError.meta,
                userId: verifiedUserId,
                categoryId
              });
            }
          }

          // Create success notification
          try {
            console.log(`[Payment Confirm] Creating notification for user: ${verifiedUserId}`);
            const categoryNames = paymentIntent.metadata?.categoryNames || 'selected categories';
            const notification = await prisma.notification.create({
              data: {
                userId: verifiedUserId,
                type: 'subscription_purchased',
                title: 'Membership Activated Successfully! 🎉',
                message: `Your membership payment of ${(paymentIntent.amount / 100).toFixed(2)} ${paymentIntent.currency.toUpperCase()} has been processed successfully. You can now bid on projects in: ${categoryNames}. Start browsing available projects now!`,
                data: JSON.stringify({
                  paymentIntentId: paymentIntent.id,
                  amount: paymentIntent.amount / 100,
                  currency: paymentIntent.currency,
                  categoryIds,
                  categoryNames,
                  activationDate: new Date().toISOString()
                }),
              },
            });
            console.log(`[Payment Confirm] Successfully created notification: ${notification.id}`);
          } catch (notificationError: any) {
            console.error('[Payment Confirm] Error creating success notification');
            console.error('[Payment Confirm] Notification error details:', {
              error: notificationError.message,
              code: notificationError.code,
              meta: notificationError.meta,
              userId: verifiedUserId
            });
          }
        }
      }

      const responseMessage = paymentIntent.status === 'succeeded' 
        ? 'Payment confirmed and membership activated successfully! You can now start bidding on projects.'
        : `Payment status: ${paymentIntent.status}. Processing your membership activation...`;
      
      return NextResponse.json({
        success: true,
        message: responseMessage,
        paymentStatus: paymentIntent.status,
        paymentIntent: {
          id: paymentIntent.id,
          status: paymentIntent.status,
          amount: paymentIntent.amount,
          currency: paymentIntent.currency,
          client_secret: paymentIntent.client_secret,
        },
        membershipDetails: paymentIntent.status === 'succeeded' ? {
          categoryNames: paymentIntent.metadata?.categoryNames?.split(', ') || [],
          activationDate: new Date().toISOString(),
          expiryDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString()
        } : null
      });

    } catch (dbError: any) {
      console.error('Database error during payment confirmation:', dbError);
      return NextResponse.json(
        { 
          error: 'Database connection error',
          message: 'Your payment was successful, but we encountered an issue updating your membership status. Our team has been notified and will resolve this shortly. Please contact support if your membership is not activated within 24 hours.',
          support: 'Contact support with payment ID and error code: DB_CONFIRM_001',
          paymentId: paymentIntentId
        },
        { status: 500 }
      );
    }

  } catch (error: any) {
    console.error('Error confirming payment:', error);
    
    let userMessage = 'An error occurred while confirming your payment.';
    let errorCode = 'CONFIRM_001';
    
    if (error.type === 'StripeInvalidRequestError') {
      userMessage = 'Payment confirmation failed due to invalid payment data. Please contact support with your payment details.';
      errorCode = 'STRIPE_CONFIRM_001';
    } else if (error.type === 'StripeAPIError') {
      userMessage = 'Payment service is temporarily unavailable for confirmation. Your payment may still be processing.';
      errorCode = 'STRIPE_API_002';
    }
    
    return NextResponse.json(
      { 
        error: 'Payment confirmation failed',
        message: userMessage,
        support: `Please contact support with error code: ${errorCode} and your payment intent ID`,
        errorCode,
        details: process.env.NODE_ENV === 'development' ? error.message : undefined
      },
      { status: 500 }
    );
  }
}