/**
 * GET /api/order-status
 * Check order payment status (for polling after redirect)
 */

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

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

export async function GET(request: NextRequest) {
  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': '30',
            '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")

    if (!token) {
      return NextResponse.json({ error: "Missing checkout token" }, { status: 400 })
    }

    // Validate token format
    const validation = OrderStatusSchema.safeParse({ token })
    if (!validation.success) {
      return NextResponse.json({ error: "Invalid checkout token" }, { status: 400 })
    }

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

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

    // Check payment status
    const isPaid = WooCommerce.isPaid(order)

    return NextResponse.json({
      success: true,
      order_id: order.id,
      paid: isPaid,
      status: order.status,
    })
  } catch (error) {
    logger.error("v0", "Order status error", {
      error: error instanceof Error ? error.message : "Unknown error",
      stack: error instanceof Error ? error.stack : undefined,
    })
    return NextResponse.json(
      {
        success: false,
        error: {
          code: "ORDER_STATUS_ERROR",
          message: error instanceof Error ? error.message : "Failed to check status",
          details: process.env.NODE_ENV === "development" ? error : undefined,
        },
      },
      { status: 500 },
    )
  }
}
