/**
 * POST /api/cancel-order
 * Cancel order and restore cart when payment is abandoned
 */

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: 5 requests per minute per IP
const rateLimiter = new RateLimit(5, 60000)

export async function POST(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': '5',
            '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()

    // Validate request
    const validation = CheckoutSessionSchema.safeParse(body)
    if (!validation.success) {
      return NextResponse.json({ error: "Invalid request" }, { status: 400 })
    }

    const { token } = 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)

    // Only cancel if order is still pending
    if (order.status === "pending") {
      await WooCommerce.cancelAndRestoreCart(context.orderId)
      
      logger.info("v0", "Order cancelled and cart restored", {
        orderId: context.orderId,
      })

      return NextResponse.json({
        success: true,
        message: "Order cancelled and cart restored",
      })
    }

    // If order is already paid, don't cancel
    if (WooCommerce.isPaid(order)) {
      return NextResponse.json({
        success: false,
        error: "Order is already paid and cannot be cancelled",
      }, { status: 400 })
    }

    return NextResponse.json({
      success: true,
      message: "Order status unchanged",
    })
  } catch (error) {
    logger.error("v0", "Cancel order error", {
      error: error instanceof Error ? error.message : "Unknown error",
      stack: error instanceof Error ? error.stack : undefined,
    })
    return NextResponse.json(
      {
        success: false,
        error: {
          code: "CANCEL_ORDER_ERROR",
          message: error instanceof Error ? error.message : "Failed to cancel order",
        },
      },
      { status: 500 },
    )
  }
}






