// routes/paymentRoutes.js
import { Router } from "express";
import { authenticate } from "../middleware/authMiddleware.js";
import { verifyPayPalOrder } from "../middleware/paypalVerification.js";
import WebsiteSubmission from "../models/websiteSubmission.js";

const router = Router();

/**
 * POST /api/payments/verify
 * Verify PayPal payment order
 * This endpoint verifies the payment without creating a submission
 */
router.post("/verify", authenticate, async (req, res) => {
  try {
    console.log('📦 Payment verification request received');
    console.log('📦 Request body:', JSON.stringify(req.body, null, 2));
    console.log('📦 Request body keys:', Object.keys(req.body));
    
    const { orderID } = req.body;

    if (!orderID) {
      console.log('❌ OrderID is missing from request body');
      return res.status(400).json({
        ok: false,
        error: 'ORDER_ID_REQUIRED',
        message: 'PayPal order ID is required'
      });
    }
    
    console.log('✅ OrderID extracted:', orderID);

    // Verify with PayPal
    const verificationResult = await verifyPayPalOrder(orderID);

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

    const { order } = verificationResult;

    // Check if payment status is valid
    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.`,
        status: order.status
      });
    }

    // Check if this order has already been used
    const existingSubmission = await WebsiteSubmission.findOne({ paymentOrderID: orderID });
    if (existingSubmission) {
      return res.status(409).json({
        ok: false,
        error: 'ORDER_ALREADY_USED',
        message: 'This payment order has already been used for a submission'
      });
    }

    return res.status(200).json({
      ok: true,
      message: 'Payment verified successfully',
      paymentDetails: {
        orderID: order.id,
        status: order.status,
        amount: order.amount,
        currency: order.currency,
        payerEmail: order.payerEmail,
        payerName: order.payerName
      }
    });

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

/**
 * GET /api/payments/order/:orderID
 * Get PayPal order details (for debugging/admin purposes)
 */
router.get("/order/:orderID", authenticate, async (req, res) => {
  try {
    const { orderID } = req.params;

    const verificationResult = await verifyPayPalOrder(orderID);

    if (!verificationResult.success) {
      return res.status(404).json({
        ok: false,
        message: 'Order not found'
      });
    }

    return res.status(200).json({
      ok: true,
      order: verificationResult.order
    });

  } catch (error) {
    console.error('Get order error:', error);
    return res.status(500).json({
      ok: false,
      message: error.message || 'Failed to retrieve order'
    });
  }
});

/**
 * POST /api/payments/webhook
 * PayPal webhook handler for IPN (Instant Payment Notification)
 * This is for future implementation if you want to handle webhooks
 */
router.post("/webhook", async (req, res) => {
  try {
    // TODO: Implement webhook verification
    // You need to verify the webhook signature from PayPal
    console.log('PayPal Webhook received:', req.body);

    const eventType = req.body.event_type;
    const resource = req.body.resource;

    // Handle different webhook events
    switch (eventType) {
      case 'PAYMENT.CAPTURE.COMPLETED':
        console.log('Payment completed:', resource.id);
        // Update payment status in database if needed
        break;
      
      case 'PAYMENT.CAPTURE.DENIED':
        console.log('Payment denied:', resource.id);
        break;
      
      default:
        console.log('Unhandled webhook event:', eventType);
    }

    // Always respond 200 to acknowledge receipt
    res.status(200).json({ received: true });

  } catch (error) {
    console.error('Webhook error:', error);
    res.status(500).json({ error: 'Webhook processing failed' });
  }
});

export default router;
