import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import prisma from '@/lib/prisma'
import { authOptions } from '@/lib/auth'

export async function GET(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions)
    if (!session?.user?.id) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const cleanId = params.id.replace('#', '').toLowerCase()

    const order = await prisma.order.findFirst({
      where: {
        id: { endsWith: cleanId },
        // Admin can see all, users only their own
        ...(session.user.role !== 'ADMIN' && { userId: session.user.id }),
      },
      include: {
        vipProduct: true,
        digitalProduct: true,
        user: { select: { name: true, email: true } },
      },
    })

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

    let responseOrder: any = {
      ...order,
      productName: order.productType === 'VIP' 
        ? `${order.vipProduct?.gameName} - ${order.vipProduct?.productName}`
        : order.digitalProduct?.name,
    }

    if (order.paymentMethod === 'qris' && order.invoiceId) {
      const invoice = await prisma.paymentInvoice.findUnique({
        where: { transactionId: order.invoiceId }
      })
      if (invoice) {
        // Need to import getQrImageUrl here
        // But since we just need the string, let's construct it manually or import it
        const encoded = encodeURIComponent(invoice.qrString || '')
        const qrImageUrl = `https://larabert-qrgen.hf.space/v1/create-qr-code?size=400x400&style=2&color=000000&data=${encoded}`
        
        responseOrder = {
          ...responseOrder,
          uniqueCode: invoice.uniqueCode,
          qrString: invoice.qrString,
          qrImageUrl: invoice.qrString ? qrImageUrl : null,
          expiresAt: invoice.expiredAt,
          totalAmount: Number(invoice.totalAmount)
        }
      }
    }

    return NextResponse.json({ order: responseOrder })
  } catch (error) {
    console.error('[ORDER GET]', error)
    return NextResponse.json({ error: 'Gagal memuat order' }, { status: 500 })
  }
}
