/**
 * 支付宝回调通知 API
 * 基于 Universal_Payment_Module v4.0 设计
 * 
 * POST /api/payment/alipay/notify
 */

import { type NextRequest, NextResponse } from "next/server"
import { PaymentFactory, SignatureError } from "@/lib/payment"

// 确保网关已注册
import "@/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()
    })

    console.log("[Alipay Notify] 收到回调:", {
      out_trade_no: params.out_trade_no,
      trade_status: params.trade_status,
      total_amount: params.total_amount,
    })

    // 创建支付宝网关
    const gateway = PaymentFactory.create("alipay_wap")

    try {
      // 解析并验证回调数据
      const notifyResult = gateway.parseNotify(params)

      if (notifyResult.status === "paid") {
        console.log("[Alipay Notify] 支付成功:", {
          tradeSn: notifyResult.tradeSn,
          platformSn: notifyResult.platformSn,
          amount: notifyResult.payAmount / 100, // 转换为元
          payTime: notifyResult.payTime,
        })

        // TODO: 更新订单状态
        // await OrderService.updateStatus(notifyResult.tradeSn, 'paid')

        // TODO: 解锁内容/开通权限
        // await ContentService.unlockForUser(notifyResult.attach?.userId, notifyResult.attach?.productId)

        // TODO: 分配佣金（如果有推荐人）
        // if (notifyResult.attach?.referralCode) {
        //   await ReferralService.distributeCommission(notifyResult)
        // }
      } else {
        console.log("[Alipay Notify] 非支付成功状态:", notifyResult.status)
      }

      // 返回成功响应
      return new NextResponse(gateway.successResponse())

    } catch (error) {
      if (error instanceof SignatureError) {
        console.error("[Alipay Notify] 签名验证失败")
        return new NextResponse(gateway.failResponse())
      }
      throw error
    }

  } catch (error) {
    console.error("[Alipay Notify] 处理失败:", error)
    return new NextResponse("fail")
  }
}
