import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import prisma from '@/lib/prisma'
import { unsuspendPteroServer } from '@/lib/pterodactyl'
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 { serverId, method } = await req.json()
    if (!serverId || !method) return NextResponse.json({ error: 'Missing serverId or method' }, { status: 400 })

    const pteroServer = await prisma.pterodactylServer.findUnique({
      where: { id: serverId },
      include: { package: true }
    })

    if (!pteroServer) return NextResponse.json({ error: 'Server tidak ditemukan' }, { status: 404 })
    if (pteroServer.userId !== session.user.id) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })

    const price = Number(pteroServer.package.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 })
      }

      await prisma.$transaction(async (tx) => {
        const newBalance = Number(user.balance) - price
        await tx.user.update({ where: { id: user.id }, data: { balance: newBalance } })

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

        const currentExpiry = pteroServer.expiresAt ? new Date(pteroServer.expiresAt) : new Date()
        const newExpiry = new Date(Math.max(currentExpiry.getTime(), new Date().getTime()))
        newExpiry.setDate(newExpiry.getDate() + pteroServer.package.durationDays)

        await tx.pterodactylServer.update({
          where: { id: pteroServer.id },
          data: { expiresAt: newExpiry, status: 'ACTIVE', lastRenewedAt: new Date() }
        })

        await tx.pterodactylRenewal.create({
          data: {
            serverId: pteroServer.id,
            amount: price,
            durationDays: pteroServer.package.durationDays,
            expiresAt: newExpiry,
          }
        })
      })

      if (pteroServer.status === 'SUSPENDED' && pteroServer.pteroServerId) {
        try {
          await unsuspendPteroServer(pteroServer.pteroServerId)
        } catch (e) {
          console.error('[PTERO UNSUSPEND FAIL]', e)
        }
      }

      return NextResponse.json({ message: 'Perpanjangan berhasil', success: true })
    }
    else if (method === 'QRIS') {
      const order = await prisma.order.create({
        data: {
          userId: user.id,
          productType: 'PTERODACTYL',
          pteroServerId: pteroServer.id,
          price: price,
          status: 'PENDING',
          paymentMethod: 'QRIS',
          notes: 'RENEWAL',
        }
      })

      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),
          },
        })

        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 })
  }
}
