/**
 * POST /api/paypal/capture-order
 * Capture an approved PayPal order and update WooCommerce
 * (mirrors the Stripe webhook success handler)
 */

import { type NextRequest, NextResponse } from "next/server"
import { Security } from "@/lib/security"
import { WooCommerce } from "@/lib/woo"
import { PayPalClient } from "@/lib/paypal"
import { Money } from "@/lib/money"
import { PayPalCaptureSchema } from "@/lib/schemas"
import { logger } from "@/lib/logger"
import { RateLimit, getClientIp } from "@/lib/rate-limit"

// Rate limit: 10 requests per minute per IP
const rateLimiter = new RateLimit(10, 60000)

export async function POST(request: NextRequest) {
  console.log("\n[v0] === PAYPAL CAPTURE ORDER REQUEST START ===")
  try {
    // Apply rate limiting
    const clientIp = getClientIp(request)
    const rateLimit = rateLimiter.check(clientIp)

    if (!rateLimit.allowed) {
      return NextResponse.json({ error: "Too many requests" }, { status: 429 })
    }

    // Validate origin
    Security.validateOrigin(request)

    // Parse and validate request
    const body = await request.json()
    const validation = PayPalCaptureSchema.safeParse(body)
    if (!validation.success) {
      return NextResponse.json({ error: "Invalid request", details: validation.error.issues }, { status: 400 })
    }

    const { token, paypal_order_id } = validation.data

    // Verify checkout token
    const context = await Security.verifyToken(token)

    // Fetch order from WooCommerce
    const order = await WooCommerce.getOrder(context.orderId)

    // Check if already paid
    if (WooCommerce.isPaid(order)) {
      logger.info("v0", "Order already paid", { orderId: order.id })
      return NextResponse.json({ success: true, capture_id: "already_paid" })
    }

    // Verify the PayPal order ID matches what we stored
    const storedPayPalOrderId = WooCommerce.getMeta(order, "_paypal_order_id") as string | undefined
    if (storedPayPalOrderId && storedPayPalOrderId !== paypal_order_id) {
      logger.error("v0", "PayPal order ID mismatch", {
        stored: storedPayPalOrderId,
        received: paypal_order_id,
      })
      return NextResponse.json({ error: "PayPal order ID mismatch" }, { status: 400 })
    }

    // Capture the PayPal order
    const captureResult = await PayPalClient.captureOrder(paypal_order_id)

    if (captureResult.status !== "COMPLETED") {
      logger.error("v0", "PayPal capture not completed", {
        status: captureResult.status,
        paypalOrderId: paypal_order_id,
      })
      return NextResponse.json(
        { error: `PayPal capture failed: status=${captureResult.status}` },
        { status: 400 },
      )
    }

    // Validate amount match
    const capture = captureResult.purchase_units[0]?.payments?.captures?.[0]
    if (!capture) {
      throw new Error("No capture found in PayPal response")
    }

    const capturedCents = Math.round(Number.parseFloat(capture.amount.value) * 100)
    const normalizedOrder = WooCommerce.normalize(order)

    logger.info("v0", "PayPal capture amount validation", {
      orderId: order.id,
      orderTotal: normalizedOrder.total_cents,
      capturedAmount: capturedCents,
    })

    try {
      Money.validateMatch(normalizedOrder.total_cents, capturedCents)
    } catch {
      logger.error("v0", "PayPal amount mismatch - CRITICAL", {
        orderId: order.id,
        expected: normalizedOrder.total_cents,
        received: capturedCents,
      })

      await WooCommerce.updateOrder(order.id, {
        status: "on-hold",
        customer_note: "Payment received but amount mismatch detected. Please contact support.",
      })

      return NextResponse.json({ success: true, capture_id: capture.id })
    }

    // Update WooCommerce order to "processing" (mirrors Stripe webhook logic)
    const orderUpdate: any = {
      status: "processing",
      date_paid: new Date().toISOString(),
      date_paid_gmt: new Date().toISOString(),
      meta_data: [
        ...order.meta_data,
        { key: "_paypal_order_id", value: paypal_order_id },
        { key: "_paypal_capture_id", value: capture.id },
        { key: "_paid_date", value: new Date().toISOString() },
        { key: "_payment_method", value: "paypal" },
        { key: "_payment_method_title", value: "PayPal" },
        { key: "_transaction_id", value: capture.id },
      ],
    }
    await WooCommerce.updateOrder(order.id, orderUpdate)

    // Clear cart after successful payment
    if (order.customer_id > 0) {
      await WooCommerce.clearCart(order.customer_id)
    }

    logger.info("v0", "PayPal order payment completed", {
      orderId: order.id,
      paypalOrderId: paypal_order_id,
      captureId: capture.id,
      customerId: order.customer_id,
    })

    return NextResponse.json({
      success: true,
      capture_id: capture.id,
    })
  } catch (error) {
    logger.error("v0", "PayPal capture error", {
      error: error instanceof Error ? error.message : "Unknown error",
      stack: error instanceof Error ? error.stack : undefined,
    })

    return NextResponse.json(
      {
        success: false,
        error: {
          code: "PAYPAL_CAPTURE_ERROR",
          message: error instanceof Error ? error.message : "Failed to capture PayPal order",
          details: process.env.NODE_ENV === "development" ? error : undefined,
        },
      },
      { status: 500 },
    )
  }
}
