/**
 * POST /api/submit-order
 * Submit order for manual payment verification (Zelle/CashApp)
 */

import { type NextRequest, NextResponse } from "next/server"
import { Security } from "@/lib/security"
import { WooCommerce } from "@/lib/woo"
import { logger } from "@/lib/logger"
import { RateLimit, getClientIp } from "@/lib/rate-limit"
import { z } from "zod"
import { AddressSchema, ContactInfoSchema } from "@/lib/schemas"

// Rate limit: 10 requests per minute per IP
const rateLimiter = new RateLimit(10, 60000)

const SubmitOrderSchema = z.object({
  token: z.string().min(1, "Checkout token is required"),
  billing_address: AddressSchema,
  shipping_address: AddressSchema.nullable().optional(),
  contact_info: ContactInfoSchema.optional(),
})

export async function POST(request: NextRequest) {
  console.log("\n[v0] === SUBMIT ORDER REQUEST START ===")
  try {
    // Apply rate limiting
    const clientIp = getClientIp(request)
    const rateLimit = rateLimiter.check(clientIp)
    console.log("[v0] Client IP:", clientIp)
    console.log("[v0] Rate limit check:", rateLimit)

    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 request body
    const body = await request.json()
    console.log("[v0] Request body received:", {
      hasToken: !!body.token,
      hasBillingAddress: !!body.billing_address,
      hasShippingAddress: !!body.shipping_address,
      hasContactInfo: !!body.contact_info,
      tokenPreview: body.token ? body.token.substring(0, 20) + "..." : "missing",
    })

    // Validate request
    const validation = SubmitOrderSchema.safeParse(body)
    if (!validation.success) {
      logger.error("v0", "Submit order validation failed", {
        body,
        errors: validation.error.issues,
        errorDetails: validation.error.flatten(),
      })
      console.error("[v0] Submit Order Validation Error:")
      console.error("Request body:", JSON.stringify(body, null, 2))
      console.error("Validation errors:", JSON.stringify(validation.error.issues, null, 2))
      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
    let context
    try {
      context = await Security.verifyToken(token)
      logger.info("v0", "Token verified successfully", {
        orderId: context.orderId,
      })
    } catch (error) {
      logger.error("v0", "Token verification failed", {
        token: token.substring(0, 20) + "...",
        error: error instanceof Error ? error.message : "Unknown error",
      })
      console.error("[v0] Token Verification Error:", error)
      throw error
    }

    // Fetch order from WooCommerce
    let order
    try {
      order = await WooCommerce.getOrder(context.orderId)
      logger.info("v0", "Order fetched successfully", {
        orderId: order.id,
        status: order.status,
        total: order.total,
        customerId: order.customer_id,
      })
      console.log("[v0] Order Details:", {
        id: order.id,
        status: order.status,
        total: order.total,
        currency: order.currency,
        customer_id: order.customer_id,
      })
    } catch (error) {
      logger.error("v0", "Failed to fetch order from WooCommerce", {
        orderId: context.orderId,
        error: error instanceof Error ? error.message : "Unknown error",
      })
      console.error("[v0] WooCommerce Order Fetch Error:", error)
      throw error
    }

    // Check if order can be paid
    if (!WooCommerce.canBePaid(order)) {
      logger.error("v0", "Order cannot be submitted for manual payment", {
        orderId: order.id,
        status: order.status,
        isPaid: WooCommerce.isPaid(order),
      })
      console.error("[v0] Order Status Error:", {
        orderId: order.id,
        currentStatus: order.status,
        canBePaid: WooCommerce.canBePaid(order),
        isPaid: WooCommerce.isPaid(order),
      })
      return NextResponse.json({
        error: "Order cannot be submitted for payment",
        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-computed total (never trust frontend)
    const normalizedOrder = WooCommerce.normalize(order)

    logger.info("v0", "Order pricing breakdown", {
      orderId: order.id,
      subtotal_cents: normalizedOrder.subtotal_cents,
      tax_cents: normalizedOrder.tax_cents,
      shipping_cost_cents: normalizedOrder.shipping_cost_cents,
      total_cents: normalizedOrder.total_cents,
      woo_original_total: order.total,
    })

    // Build update data for WooCommerce order
    const updateData: any = {}

    // Set billing address with contact info
    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

    // Set shipping address (use billing if not provided)
    if (shipping_address) {
      updateData.shipping = WooCommerce.toWooAddress(shipping_address)
      console.log("[v0] Using separate shipping address")
    } else {
      updateData.shipping = WooCommerce.toWooAddress(billing_address)
      console.log("[v0] Using billing address for shipping (same as billing)")
    }

    // Build metadata using setMeta pattern for proper key deduplication
    let metaData = order.meta_data
    metaData = WooCommerce.setMeta(
      { ...order, meta_data: metaData },
      "_payment_method",
      "manual"
    )
    metaData = WooCommerce.setMeta(
      { ...order, meta_data: metaData },
      "_payment_method_title",
      "Zelle / CashApp"
    )
    metaData = WooCommerce.setMeta(
      { ...order, meta_data: metaData },
      "_manual_payment_status",
      "pending-screenshot"
    )
    metaData = WooCommerce.setMeta(
      { ...order, meta_data: metaData },
      "_order_submitted_at",
      new Date().toISOString()
    )
    metaData = WooCommerce.setMeta(
      { ...order, meta_data: metaData },
      "_checkout_address_updated",
      new Date().toISOString()
    )

    updateData.meta_data = metaData
    updateData.status = "pending"
    updateData.customer_note = "Order submitted. Awaiting manual payment via Zelle or CashApp."

    console.log("[v0] Updating order with manual payment data:", {
      orderId: order.id,
      hasBilling: !!updateData.billing,
      hasShipping: !!updateData.shipping,
      hasContactInfo: !!contact_info,
      metaKeysAdded: ["_payment_method", "_payment_method_title", "_manual_payment_status", "_order_submitted_at", "_checkout_address_updated"],
    })

    await WooCommerce.updateOrder(order.id, updateData)

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

    return NextResponse.json({
      success: true,
      order_id: order.id,
      total: normalizedOrder.total_cents,
      currency: normalizedOrder.currency,
    })
  } catch (error) {
    logger.error("v0", "Submit order error", {
      error: error instanceof Error ? error.message : "Unknown error",
      stack: error instanceof Error ? error.stack : undefined,
    })

    // Enhanced console logging for debugging
    console.error("\n=== [v0] SUBMIT ORDER ERROR ===")
    console.error("Error Type:", error instanceof Error ? error.constructor.name : typeof error)
    console.error("Error Message:", error instanceof Error ? error.message : String(error))
    if (error instanceof Error && error.stack) {
      console.error("Stack Trace:", error.stack)
    }
    console.error("================================\n")

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