import { NextRequest, NextResponse } from 'next/server'
import { authenticateH2H, h2hUnauthorized } from '@/lib/h2h-auth'
import prisma from '@/lib/prisma'

export const dynamic = 'force-dynamic'

export async function GET(req: NextRequest, { params }: { params: { id: string } }) {
  const h2hUser = await authenticateH2H(req)
  if (!h2hUser) return h2hUnauthorized()

  try {
    const order = await prisma.order.findFirst({
      where: { id: params.id, userId: h2hUser.id },
      include: {
        vipProduct: { select: { gameName: true, productName: true } },
        digitalProduct: { select: { name: true } },
      },
    })

    if (!order) {
      return NextResponse.json({ success: false, error: 'Order tidak ditemukan' }, { status: 404 })
    }

    return NextResponse.json({
      success: true,
      data: {
        orderId: order.id,
        status: order.status,
        productType: order.productType,
        productName: order.vipProduct
          ? `${order.vipProduct.gameName} - ${order.vipProduct.productName}`
          : order.digitalProduct?.name || 'Unknown',
        price: order.price,
        targetId: order.targetId,
        deliveryData: order.status === 'SUCCESS' ? order.deliveryData : null,
        createdAt: order.createdAt,
      },
    })
  } catch (error) {
    return NextResponse.json({ success: false, error: 'Gagal cek order' }, { status: 500 })
  }
}
