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

export async function POST(request: Request) {
  try {
    const paymentData: PaymentRequest = await request.json()

    if (!paymentData.sourceId) {
      return Response.json({ 
        success: false, 
        error: "Payment source ID is required" 
      }, { status: 400 })
    }

    if (!paymentData.amount || paymentData.amount <= 0) {
      return Response.json({ 
        success: false, 
        error: "Valid payment amount is required" 
      }, { status: 400 })
    }

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

    // Create payment request
    const paymentRequest = {
      sourceId: paymentData.sourceId,
      idempotencyKey: crypto.randomUUID(),
      amountMoney: {
        amount: BigInt(Math.round(paymentData.amount * 100)), // Convert to cents
        currency: paymentData.currency || "USD",
      },
      locationId: locationId,
      ...(paymentData.orderId && { orderId: paymentData.orderId }),
      buyerEmailAddress: paymentData.customerInfo.email,
      note: `Aunty Sparkles order - ${paymentData.customerInfo.name}`,
      autocomplete: true,
      acceptPartialAuthorization: false,
    }

    console.log("Processing Square payment:", {
      amount: paymentData.amount,
      currency: paymentData.currency,
      customerEmail: paymentData.customerInfo.email,
      orderId: paymentData.orderId
    })

    const response = await paymentsApi.createPayment(paymentRequest)

    if (response.result.payment) {
      const payment = response.result.payment
      
      console.log("Payment processed successfully:", {
        paymentId: payment.id,
        status: payment.status,
        amount: payment.amountMoney?.amount
      })

      return Response.json({
        success: true,
        payment: {
          id: payment.id,
          status: payment.status,
          amount: paymentData.amount,
          currency: paymentData.currency,
          receiptUrl: payment.receiptUrl,
          orderId: payment.orderId
        }
      })
    } else {
      throw new Error("Payment processing failed - no payment returned")
    }

  } catch (error) {
    console.error("Square payment error:", error)
    
    // Handle specific Square API errors
    let errorMessage = "Payment processing failed"
    if (error instanceof Error) {
      if (error.message.includes("CARD_DECLINED")) {
        errorMessage = "Your card was declined. Please try a different payment method."
      } else if (error.message.includes("INSUFFICIENT_FUNDS")) {
        errorMessage = "Insufficient funds. Please try a different payment method."
      } else if (error.message.includes("INVALID_CARD")) {
        errorMessage = "Invalid card information. Please check your card details."
      } else {
        errorMessage = error.message
      }
    }

    return Response.json({ 
      success: false, 
      error: errorMessage 
    }, { status: 500 })
  }
}
