import { getSquareClient, getSquareLocationId } from "@/lib/square-client"

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url)
    const catalogObjectId = searchParams.get("catalogObjectId")

    if (!catalogObjectId) {
      return Response.json({ 
        success: false, 
        error: "catalogObjectId parameter is required" 
      }, { status: 400 })
    }

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

    const response = await inventoryApi.batchRetrieveInventoryCounts({
      catalogObjectIds: [catalogObjectId],
      locationIds: [locationId],
    })

    const inventory = response.result.counts?.[0]
    const quantity = inventory ? parseInt(inventory.quantity || "0") : 0
    const state = inventory?.state || "NONE"

    return Response.json({ 
      success: true, 
      quantity,
      state,
      isAvailable: quantity > 0 && state === "IN_STOCK"
    })

  } catch (error) {
    console.error("Square inventory error:", error)
    return Response.json({ 
      success: false, 
      error: error instanceof Error ? error.message : "Inventory fetch failed",
      quantity: 0,
      isAvailable: false
    }, { status: 500 })
  }
}
