/**
 * POST /api/paypal/create-order
 * Create a PayPal order (mirrors the Stripe payment-intent route)
 */

import { type NextRequest, NextResponse } from "next/server"
import { Security } from "@/lib/security"
import { WooCommerce } from "@/lib/woo"
import { PayPalClient } from "@/lib/paypal"
import { PaymentIntentSchema } 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 CREATE 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. Please try again later." },
        {
          status: 429,
          headers: {
            "X-RateLimit-Limit": "10",
            "X-RateLimit-Remaining": "0",
            "X-RateLimit-Reset": new Date(rateLimit.resetTime).toISOString(),
          },
        },
      )
    }

    // Validate origin (CORS)
    Security.validateOrigin(request)

    // Parse and validate request body (reuse same schema as Stripe flow)
    const body = await request.json()
    const validation = PaymentIntentSchema.safeParse(body)
    if (!validation.success) {
      logger.error("v0", "PayPal create order validation failed", {
        errors: validation.error.issues,
      })
      return NextResponse.json({ error: "Invalid request", details: validation.error.issues }, { status: 400 })
    }

    const { token, billing_address, shipping_address, contact_info } = validation.data

    // Verify token and get order context
    const context = await Security.verifyToken(token)

    // Fetch order from WooCommerce
    const order = await WooCommerce.getOrder(context.orderId)

    // Check if order can be paid
    if (!WooCommerce.canBePaid(order)) {
      return NextResponse.json(
        {
          error: "Order cannot be paid",
          details: {
            orderId: order.id,
            status: order.status,
            reason: WooCommerce.isPaid(order) ? "Order is already paid" : "Order status is not pending",
          },
        },
        { status: 400 },
      )
    }

    // Normalize order to get server-calculated amount
    const normalizedOrder = WooCommerce.normalize(order)

    logger.info("v0", "PayPal order pricing", {
      orderId: order.id,
      total_cents: normalizedOrder.total_cents,
    })

    // Check if a PayPal order already exists for this WooCommerce order
    let paypalOrderId: string
    if (normalizedOrder.paypal_order_id) {
      try {
        const existing = await PayPalClient.getOrder(normalizedOrder.paypal_order_id)
        if (existing.status === "CREATED") {
          paypalOrderId = normalizedOrder.paypal_order_id
          logger.info("v0", "Reusing existing PayPal order", { paypalOrderId })
        } else {
          // Existing order is no longer usable, create new
          const paypalOrder = await PayPalClient.createOrder({
            orderId: order.id,
            amountCents: normalizedOrder.total_cents,
            currency: normalizedOrder.currency,
            description: `Order #${order.id}`,
          })
          paypalOrderId = paypalOrder.id
        }
      } catch {
        // Existing order lookup failed, create new
        const paypalOrder = await PayPalClient.createOrder({
          orderId: order.id,
          amountCents: normalizedOrder.total_cents,
          currency: normalizedOrder.currency,
          description: `Order #${order.id}`,
        })
        paypalOrderId = paypalOrder.id
      }
    } else {
      // Create new PayPal order
      const paypalOrder = await PayPalClient.createOrder({
        orderId: order.id,
        amountCents: normalizedOrder.total_cents,
        currency: normalizedOrder.currency,
        description: `Order #${order.id}`,
      })
      paypalOrderId = paypalOrder.id
    }

    // Store PayPal order ID in WooCommerce meta
    const metaData = WooCommerce.setMeta(order, "_paypal_order_id", paypalOrderId)
    await WooCommerce.updateOrder(order.id, { meta_data: metaData })

    // Update addresses and contact info (same logic as payment-intent route)
    if (billing_address || shipping_address || contact_info) {
      const updateData: any = {}

      if (billing_address) {
        const billingData = WooCommerce.toWooAddress(billing_address)

        if (contact_info) {
          ;(billingData as any).email = contact_info.email
          ;(billingData as any).phone = contact_info.phone
        }

        updateData.billing = billingData

        if (shipping_address === null) {
          updateData.shipping = WooCommerce.toWooAddress(billing_address)
        }
      } else if (contact_info) {
        updateData.billing = {
          email: contact_info.email,
          phone: contact_info.phone,
        }
      }

      if (shipping_address) {
        updateData.shipping = WooCommerce.toWooAddress(shipping_address)
      }

      const addressMetadata = [
        ...order.meta_data,
        {
          key: "_checkout_address_updated",
          value: new Date().toISOString(),
        },
      ]
      updateData.meta_data = addressMetadata

      await WooCommerce.updateOrder(order.id, updateData)
    }

    return NextResponse.json({
      success: true,
      paypal_order_id: paypalOrderId,
    })
  } catch (error) {
    logger.error("v0", "PayPal create order error", {
      error: error instanceof Error ? error.message : "Unknown error",
      stack: error instanceof Error ? error.stack : undefined,
    })

    return NextResponse.json(
      {
        success: false,
        error: {
          code: "PAYPAL_CREATE_ORDER_ERROR",
          message: error instanceof Error ? error.message : "Failed to create PayPal order",
          details: process.env.NODE_ENV === "development" ? error : undefined,
        },
      },
      { status: 500 },
    )
  }
}
