import { type NextRequest, NextResponse } from "next/server"
import { AlipayService } from "@/lib/payment/alipay"

export async function POST(request: NextRequest) {
  try {
    const formData = await request.formData()
    const params: Record<string, string> = {}

    formData.forEach((value, key) => {
      params[key] = value.toString()
    })

    // 初始化支付宝服务
    const alipay = new AlipayService({
      appId: process.env.ALIPAY_APP_ID || "wx432c93e275548671",
      partnerId: process.env.ALIPAY_PARTNER_ID || "2088511801157159",
      key: process.env.ALIPAY_KEY || "lz6ey1h3kl9zqkgtjz3avb5gk37wzbrp",
      returnUrl: "",
      notifyUrl: "",
    })

    // 验证签名
    const isValid = alipay.verifySign(params)

    if (!isValid) {
      console.error("[v0] Alipay signature verification failed")
      return new NextResponse("fail")
    }

    const { out_trade_no, trade_status, buyer_id, total_amount } = params

    // 只处理支付成功的通知
    if (trade_status === "TRADE_SUCCESS" || trade_status === "TRADE_FINISHED") {
      console.log("[v0] Alipay payment success:", {
        orderId: out_trade_no,
        amount: total_amount,
        buyerId: buyer_id,
      })

      // TODO: 更新订单状态、解锁内容、分配佣金
    }

    return new NextResponse("success")
  } catch (error) {
    console.error("[v0] Alipay notify error:", error)
    return new NextResponse("fail")
  }
}
