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

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { userId, type, sectionId, sectionTitle, amount, paymentMethod, referralCode } = body

    // Validate required fields
    if (!userId || !type || !amount || !paymentMethod) {
      return NextResponse.json({ code: 400, message: "缺少必要参数" }, { status: 400 })
    }

    // Generate order ID
    const orderId = `ORDER_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`

    // Create order object
    const order = {
      orderId,
      userId,
      type, // "section" | "fullbook"
      sectionId: type === "section" ? sectionId : undefined,
      sectionTitle: type === "section" ? sectionTitle : undefined,
      amount,
      paymentMethod, // "wechat" | "alipay" | "usdt" | "paypal"
      referralCode,
      status: "pending", // pending | completed | failed | refunded
      createdAt: new Date().toISOString(),
      expireAt: new Date(Date.now() + 30 * 60 * 1000).toISOString(), // 30 minutes
    }

    // According to the payment method, create a payment order
    let paymentData = null

    if (paymentMethod === "alipay") {
      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: process.env.ALIPAY_RETURN_URL || `${process.env.NEXT_PUBLIC_BASE_URL}/payment/success`,
        notifyUrl: process.env.ALIPAY_NOTIFY_URL || `${process.env.NEXT_PUBLIC_BASE_URL}/api/payment/alipay/notify`,
      })

      paymentData = alipay.createOrder({
        outTradeNo: orderId,
        subject: type === "section" ? `购买章节: ${sectionTitle}` : "购买整本书",
        totalAmount: amount,
        body: `知识付费-书籍购买`,
      })
    } else if (paymentMethod === "wechat") {
      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: process.env.WECHAT_NOTIFY_URL || `${process.env.NEXT_PUBLIC_BASE_URL}/api/payment/wechat/notify`,
      })

      const clientIp = request.headers.get("x-forwarded-for") || request.headers.get("x-real-ip") || "127.0.0.1"

      paymentData = await wechat.createOrder({
        outTradeNo: orderId,
        body: type === "section" ? `购买章节: ${sectionTitle}` : "购买整本书",
        totalFee: amount,
        spbillCreateIp: clientIp.split(",")[0].trim(),
      })
    }

    return NextResponse.json({
      code: 0,
      message: "订单创建成功",
      data: {
        ...order,
        paymentData,
      },
    })
  } catch (error) {
    console.error("[v0] Create order error:", error)
    return NextResponse.json(
      {
        code: 500,
        message: error instanceof Error ? error.message : "服务器错误",
      },
      { status: 500 },
    )
  }
}
