// middleware/paypalVerification.js
import paypal from '@paypal/checkout-server-sdk';
import paypalClient from '../config/paypal.js';

/**
 * Verifies PayPal order by order ID
 * @param {string} orderID - PayPal order ID to verify
 * @returns {Promise<Object>} - Order details if valid
 * 
 * NOTE: Using deprecated SDK temporarily due to authentication issues with new SDK
 * TODO: Migrate to @paypal/paypal-server-sdk once auth issue is resolved
 */
export const verifyPayPalOrder = async (orderID) => {
  try {
    if (!orderID) {
      throw new Error('Order ID is required');
    }

    // Log the environment mode for debugging
    const paypalMode = process.env.PAYPAL_MODE || 'sandbox';
    console.log(`🔍 Verifying PayPal order in ${paypalMode.toUpperCase()} mode:`, orderID);

    const client = paypalClient();
    const request = new paypal.orders.OrdersGetRequest(orderID);

    // Execute the request to get order details
    const response = await client.execute(request);
    const order = response.result;

    console.log('✅ PayPal Order Retrieved:', {
      id: order.id,
      status: order.status,
      amount: order.purchase_units[0]?.amount?.value,
      currency: order.purchase_units[0]?.amount?.currency_code
    });

    return {
      success: true,
      order: {
        id: order.id,
        status: order.status,
        payerEmail: order.payer?.email_address || null,
        payerName: order.payer?.name?.given_name && order.payer?.name?.surname
          ? `${order.payer.name.given_name} ${order.payer.name.surname}`
          : null,
        amount: order.purchase_units[0]?.amount?.value,
        currency: order.purchase_units[0]?.amount?.currency_code,
        createTime: order.create_time,
        updateTime: order.update_time,
        rawResponse: order
      }
    };
  } catch (error) {
    console.error('❌ PayPal Order Verification Failed:', error);

    if (error.statusCode === 404) {
      throw new Error('Order not found');
    } else if (error.statusCode === 401 || error.statusCode === 403) {
      throw new Error('PayPal authentication failed. Check credentials.');
    } else {
      throw new Error(`PayPal verification error: ${error.message}`);
    }
  }
};

/**
 * Middleware to verify payment before processing submission
 */
export const verifyPaymentMiddleware = async (req, res, next) => {
  try {
    const { paymentOrderID } = req.body;

    if (!paymentOrderID) {
      return res.status(400).json({
        ok: false,
        error: 'PAYMENT_REQUIRED',
        message: 'Payment order ID is required'
      });
    }

    // Verify the payment with PayPal
    const verificationResult = await verifyPayPalOrder(paymentOrderID);

    if (!verificationResult.success) {
      return res.status(400).json({
        ok: false,
        error: 'PAYMENT_VERIFICATION_FAILED',
        message: 'Payment verification failed'
      });
    }

    const { order } = verificationResult;

    // Check if payment is completed or approved
    if (order.status !== 'COMPLETED' && order.status !== 'APPROVED') {
      return res.status(400).json({
        ok: false,
        error: 'PAYMENT_NOT_COMPLETED',
        message: `Payment status is ${order.status}. Expected COMPLETED or APPROVED.`
      });
    }

    // Attach verified payment info to request for use in route handler
    req.verifiedPayment = {
      orderID: order.id,
      status: order.status,
      amount: order.amount,
      currency: order.currency,
      payerEmail: order.payerEmail,
      payerName: order.payerName,
      verifiedAt: new Date()
    };

    next();
  } catch (error) {
    console.error('Payment verification middleware error:', error);
    return res.status(500).json({
      ok: false,
      error: 'PAYMENT_VERIFICATION_ERROR',
      message: error.message || 'Failed to verify payment'
    });
  }
};

export default {
  verifyPayPalOrder,
  verifyPaymentMiddleware
};
