/**
 * 查询支付状态 API
 * 基于 Universal_Payment_Module v4.0 设计
 * 
 * GET /api/payment/query?tradeSn=xxx&gateway=wechat_native|alipay_wap
 */

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

// 确保网关已注册
import "@/lib/payment/alipay"
import "@/lib/payment/wechat"

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const tradeSn = searchParams.get("tradeSn")
    const gateway = searchParams.get("gateway") // 可选：指定支付网关

    if (!tradeSn) {
      return NextResponse.json(
        { code: 400, message: "缺少交易号", data: null },
        { status: 400 }
      )
    }

    console.log("[Payment Query] 查询交易状态:", { tradeSn, gateway })

    let wechatResult = null
    let alipayResult = null
    
    // 如果指定了网关，只查询该网关
    if (gateway) {
      try {
        const paymentGateway = PaymentFactory.create(gateway)
        const result = await paymentGateway.queryTrade(tradeSn)
        
        return NextResponse.json({
          code: 200,
          message: "success",
          data: {
            tradeSn: result?.tradeSn || tradeSn,
            status: result?.status || "paying",
            platformSn: result?.platformSn || null,
            payAmount: result?.payAmount || null,
            payTime: result?.payTime || null,
            gateway,
          },
        })
      } catch (e) {
        console.log(`[Payment Query] ${gateway} 查询失败:`, e)
        return NextResponse.json({
          code: 200,
          message: "success",
          data: {
            tradeSn,
            status: "paying",
            platformSn: null,
            payAmount: null,
            payTime: null,
            gateway,
          },
        })
      }
    }

    // 没有指定网关时，先查询微信
    try {
      const wechatGateway = PaymentFactory.create("wechat_native")
      wechatResult = await wechatGateway.queryTrade(tradeSn)
      
      if (wechatResult && wechatResult.status === "paid") {
        console.log("[Payment Query] 微信支付成功:", { tradeSn, status: wechatResult.status })
        return NextResponse.json({
          code: 200,
          message: "success",
          data: {
            tradeSn: wechatResult.tradeSn,
            status: wechatResult.status,
            platformSn: wechatResult.platformSn,
            payAmount: wechatResult.payAmount,
            payTime: wechatResult.payTime,
            gateway: "wechat_native",
          },
        })
      }
    } catch (e) {
      console.log("[Payment Query] 微信查询异常:", e)
    }

    // 再查询支付宝
    try {
      const alipayGateway = PaymentFactory.create("alipay_wap")
      alipayResult = await alipayGateway.queryTrade(tradeSn)
      
      if (alipayResult && alipayResult.status === "paid") {
        console.log("[Payment Query] 支付宝支付成功:", { tradeSn, status: alipayResult.status })
        return NextResponse.json({
          code: 200,
          message: "success",
          data: {
            tradeSn: alipayResult.tradeSn,
            status: alipayResult.status,
            platformSn: alipayResult.platformSn,
            payAmount: alipayResult.payAmount,
            payTime: alipayResult.payTime,
            gateway: "alipay_wap",
          },
        })
      }
    } catch (e) {
      console.log("[Payment Query] 支付宝查询异常:", e)
    }

    // 如果都未支付，优先返回微信的状态（因为更可靠）
    const result = wechatResult || alipayResult

    // 返回等待支付状态
    return NextResponse.json({
      code: 200,
      message: "success",
      data: {
        tradeSn,
        status: result?.status || "paying",
        platformSn: result?.platformSn || null,
        payAmount: result?.payAmount || null,
        payTime: result?.payTime || null,
        gateway: null,
      },
    })
  } catch (error) {
    console.error("[Payment Query] Error:", error)
    return NextResponse.json(
      {
        code: 500,
        message: error instanceof Error ? error.message : "服务器错误",
        data: null,
      },
      { status: 500 }
    )
  }
}
