/**
 * GET /api/checkout-session
 * Load checkout page data (order + totals)
 */

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

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

export async function GET(request: NextRequest) {
  console.log("\n[v0] === CHECKOUT SESSION REQUEST START ===")
  try {
    // Apply rate limiting
    const clientIp = getClientIp(request)
    const rateLimit = rateLimiter.check(clientIp)
    console.log("[v0] Client IP:", clientIp)
    
    if (!rateLimit.allowed) {
      return NextResponse.json(
        { error: "Too many requests. Please try again later." },
        { 
          status: 429,
          headers: {
            'X-RateLimit-Limit': '20',
            'X-RateLimit-Remaining': '0',
            'X-RateLimit-Reset': new Date(rateLimit.resetTime).toISOString(),
          }
        }
      )
    }

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

    // Get token from query params
    const token = request.nextUrl.searchParams.get("token")
    console.log("[v0] Token received:", token ? token.substring(0, 20) + "..." : "missing")

    if (!token) {
      console.error("[v0] ERROR: Missing checkout token")
      return NextResponse.json({ error: "Missing checkout token" }, { status: 400 })
    }

    // Validate token format
    const validation = CheckoutSessionSchema.safeParse({ token })
    if (!validation.success) {
      console.error("[v0] ERROR: Invalid token format:", validation.error.issues)
      return NextResponse.json({ error: "Invalid checkout token" }, { status: 400 })
    }

    // Verify token and get order context
    const context = await Security.verifyToken(token)
    console.log("[v0] Token verified, Order ID:", context.orderId)

    // Fetch order from WooCommerce
    const order = await WooCommerce.getOrder(context.orderId)
    console.log("[v0] Order fetched:", {
      id: order.id,
      status: order.status,
      total: order.total,
      currency: order.currency,
      customer_id: order.customer_id,
      items: order.line_items.length,
    })

    // Check if order can be displayed
    if (!WooCommerce.canBePaid(order) && !WooCommerce.isPaid(order)) {
      console.error("[v0] ERROR: Order cannot be paid", {
        orderId: order.id,
        status: order.status,
        canBePaid: WooCommerce.canBePaid(order),
        isPaid: WooCommerce.isPaid(order),
      })
      return NextResponse.json({ error: "Order cannot be paid" }, { status: 400 })
    }

    // Normalize order data for frontend
    const normalizedOrder = WooCommerce.normalize(order)
    console.log("[v0] Order normalized successfully")
    console.log("[v0] === CHECKOUT SESSION REQUEST END ===\n")

    return NextResponse.json({
      success: true,
      order: normalizedOrder,
    })
  } catch (error) {
    logger.error("v0", "Checkout session error", {
      error: error instanceof Error ? error.message : "Unknown error",
      stack: error instanceof Error ? error.stack : undefined,
    })
    return NextResponse.json(
      {
        success: false,
        error: {
          code: "CHECKOUT_SESSION_ERROR",
          message: error instanceof Error ? error.message : "Failed to load checkout",
          details: process.env.NODE_ENV === "development" ? error : undefined,
        },
      },
      { status: 500 },
    )
  }
}
