import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import prisma from '@/lib/prisma'
import { fulfillPteroOrder } from '@/lib/pterodactyl-fulfillment'
import { generateQris, getQrImageUrl } from '@/lib/cashify'

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

    const { packageId, method, pteroUsername, pteroPassword } = await req.json()
    if (!packageId || !method) return NextResponse.json({ error: 'Missing packageId or method' }, { status: 400 })
    if (!pteroUsername?.trim()) return NextResponse.json({ error: 'Nickname panel wajib diisi' }, { status: 400 })
    if (!pteroPassword?.trim() || pteroPassword.trim().length < 8) return NextResponse.json({ error: 'Password panel minimal 8 karakter' }, { status: 400 })

    const pkg = await prisma.pterodactylPackage.findUnique({ where: { id: packageId } })
    if (!pkg || !pkg.isActive) return NextResponse.json({ error: 'Paket tidak ditemukan atau tidak aktif' }, { status: 404 })

    const price = Number(pkg.price)

    const user = await prisma.user.findUnique({ where: { id: session.user.id } })
    if (!user) return NextResponse.json({ error: 'User tidak valid' }, { status: 400 })

    if (method === 'BALANCE') {
      if (Number(user.balance) < price) {
        return NextResponse.json({ error: 'Saldo tidak mencukupi' }, { status: 400 })
      }

      const result = await prisma.$transaction(async (tx) => {
        const newBalance = Number(user.balance) - price

        await tx.user.update({ where: { id: user.id }, data: { balance: newBalance } })

        const order = await tx.order.create({
          data: {
            userId: user.id,
            productType: 'PTERODACTYL',
            pteroPackageId: pkg.id,
            price: price,
            status: 'SUCCESS',
            paymentMethod: 'BALANCE',
            paidAt: new Date(),
          }
        })

        await tx.walletTransaction.create({
          data: {
            userId: user.id,
            type: 'PAYMENT',
            amount: price,
            balanceBefore: user.balance,
            balanceAfter: newBalance,
            description: `Pembelian Server: ${pkg.name}`,
            status: 'SUCCESS',
            orderId: order.id,
          }
        })

        const pteroServer = await tx.pterodactylServer.create({
          data: { userId: user.id, packageId: pkg.id, status: 'PENDING', pteroUsername: pteroUsername.trim(), pteroPassword: pteroPassword.trim() }
        })

        await tx.order.update({ where: { id: order.id }, data: { pteroServerId: pteroServer.id } })

        return pteroServer.id
      })

      try {
        await fulfillPteroOrder(result)
        return NextResponse.json({ message: 'Pembayaran berhasil, server sedang disiapkan', success: true })
      } catch (err: any) {
        console.error('[PTERO FULFILL FAIL]', err)
        // Update order status to failed since fulfillment failed
        await prisma.pterodactylServer.update({ where: { id: result }, data: { status: 'EXPIRED' } })
        return NextResponse.json({ error: `Gagal membuat server: ${err.message}` }, { status: 500 })
      }
    }
    else if (method === 'QRIS') {
      const order = await prisma.order.create({
        data: {
          userId: user.id,
          productType: 'PTERODACTYL',
          pteroPackageId: pkg.id,
          price: price,
          status: 'PENDING',
          paymentMethod: 'QRIS',
        }
      })

      const pteroServer = await prisma.pterodactylServer.create({
        data: { userId: user.id, packageId: pkg.id, status: 'PENDING', pteroUsername: pteroUsername.trim(), pteroPassword: pteroPassword.trim() }
      })

      await prisma.order.update({ where: { id: order.id }, data: { pteroServerId: pteroServer.id } })

      try {
        const qrisResult = await generateQris({
          amount: price,
          expiredInMinutes: 30,
          useUniqueCode: true,
        })

        const paymentUrl = getQrImageUrl(qrisResult.qr_string)

        await prisma.order.update({
          where: { id: order.id },
          data: {
            invoiceId: qrisResult.transactionId,
            invoiceUrl: paymentUrl,
            totalAmount: qrisResult.totalAmount,
          }
        })

        await prisma.paymentInvoice.create({
          data: {
            transactionId: qrisResult.transactionId,
            type: 'ORDER_PAYMENT',
            userId: user.id,
            orderId: order.id,
            amount: price,
            totalAmount: qrisResult.totalAmount,
            uniqueCode: qrisResult.uniqueNominal,
            qrString: qrisResult.qr_string,
            status: 'pending',
            packageIds: JSON.stringify(qrisResult.packageIds),
            expiredAt: new Date(Date.now() + 30 * 60 * 1000),
          },
        })

        await prisma.pterodactylServer.update({
          where: { id: pteroServer.id },
          data: { invoiceId: qrisResult.transactionId }
        })

        return NextResponse.json({
          message: 'Berhasil generate QRIS',
          invoiceUrl: paymentUrl,
          totalAmount: qrisResult.totalAmount,
          orderId: order.id
        })
      } catch (error: any) {
        await prisma.order.update({ where: { id: order.id }, data: { status: 'FAILED' } })
        return NextResponse.json({ error: error.message }, { status: 400 })
      }
    }

    return NextResponse.json({ error: 'Metode pembayaran tidak didukung' }, { status: 400 })

  } catch (error: any) {
    console.error(error)
    return NextResponse.json({ error: 'Terjadi kesalahan sistem' }, { status: 500 })
  }
}
