import { type NextRequest, NextResponse } from "next/server"
import { WechatPayService } from "@/lib/payment/wechat"

export async function POST(request: NextRequest) {
  try {
    const xmlData = await request.text()

    const wechat = new WechatPayService({
      appId: process.env.WECHAT_APP_ID || "wx432c93e275548671",
      appSecret: process.env.WECHAT_APP_SECRET || "25b7e7fdb7998e5107e242ebb6ddabd0",
      mchId: process.env.WECHAT_MCH_ID || "1318592501",
      apiKey: process.env.WECHAT_API_KEY || "wx3e31b068be59ddc131b068be59ddc2",
      notifyUrl: "",
    })

    // 解析XML数据
    const params = await wechat["parseXML"](xmlData)

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

    if (!isValid) {
      console.error("[v0] WeChat signature verification failed")
      return new NextResponse(
        "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>",
        {
          headers: { "Content-Type": "application/xml" },
        },
      )
    }

    const { out_trade_no, result_code, total_fee, openid } = params

    if (result_code === "SUCCESS") {
      console.log("[v0] WeChat payment success:", {
        orderId: out_trade_no,
        amount: Number.parseInt(total_fee) / 100,
        openid,
      })

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

    return new NextResponse(
      "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>",
      {
        headers: { "Content-Type": "application/xml" },
      },
    )
  } catch (error) {
    console.error("[v0] WeChat notify error:", error)
    return new NextResponse(
      "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[系统错误]]></return_msg></xml>",
      {
        headers: { "Content-Type": "application/xml" },
      },
    )
  }
}
