import { getSquareClient, getSquareLocationId } from "@/lib/square-client"
import type { CustomerInfo, CartItem } from "@/lib/square-types"

export async function POST(request: Request) {
  try {
    const { items, customerInfo }: { items: CartItem[], customerInfo: CustomerInfo } = await request.json()

    if (!items || items.length === 0) {
      return Response.json({ 
        success: false, 
        error: "No items provided" 
      }, { status: 400 })
    }

    if (!customerInfo.name || !customerInfo.email) {
      return Response.json({ 
        success: false, 
        error: "Customer name and email are required" 
      }, { status: 400 })
    }

    const client = await getSquareClient()
    const locationId = getSquareLocationId()
    const ordersApi = client.ordersApi

    // Calculate total amount
    const totalAmount = items.reduce((sum, item) => sum + (item.price * item.quantity), 0)

    // Create order request
    const orderRequest = {
      order: {
        locationId: locationId,
        lineItems: items.map(item => ({
          catalogObjectId: item.variationId,
          quantity: item.quantity.toString(),
          name: item.name,
          note: item.description || "",
          basePriceMoney: {
            amount: BigInt(Math.round(item.price * 100)), // Convert to cents
            currency: "USD",
          },
        })),
        metadata: {
          customerName: customerInfo.name,
          customerEmail: customerInfo.email,
          customerPhone: customerInfo.phone || "",
          ...(customerInfo.address && {
            shippingAddress: JSON.stringify(customerInfo.address)
          })
        },
        state: "OPEN",
        totalMoney: {
          amount: BigInt(Math.round(totalAmount * 100)),
          currency: "USD"
        }
      },
      idempotencyKey: crypto.randomUUID(),
    }

    console.log("Creating Square order:", {
      itemCount: items.length,
      totalAmount,
      customerEmail: customerInfo.email
    })

    const response = await ordersApi.createOrder(orderRequest)

    if (response.result.order) {
      console.log("Order created successfully:", response.result.order.id)
      
      return Response.json({
        success: true,
        order: {
          id: response.result.order.id,
          state: response.result.order.state,
          totalAmount: totalAmount,
          lineItems: response.result.order.lineItems?.length || 0
        }
      })
    } else {
      throw new Error("Order creation failed - no order returned")
    }

  } catch (error) {
    console.error("Square order creation error:", error)
    return Response.json({ 
      success: false, 
      error: error instanceof Error ? error.message : "Order creation failed" 
    }, { status: 500 })
  }
}
