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

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

    const { productId, target, quantity, method } = await req.json()

    if (!productId || !target || !quantity || !method) {
      return NextResponse.json({ error: 'Data tidak lengkap' }, { status: 400 })
    }

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

    const qty = Number(quantity)
    if (qty < smmProduct.minOrder) return NextResponse.json({ error: `Minimal order adalah ${smmProduct.minOrder}` }, { status: 400 })
    if (qty > smmProduct.maxOrder) return NextResponse.json({ error: `Maksimal order adalah ${smmProduct.maxOrder}` }, { status: 400 })

    // Zaynflazz harga per 1000
    const totalPrice = (qty / 1000) * Number(smmProduct.sellPrice)

    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) < totalPrice) {
        return NextResponse.json({ error: 'Saldo tidak mencukupi' }, { status: 400 })
      }

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

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

        const order = await tx.order.create({
          data: {
            userId: user.id,
            productType: 'SMM',
            smmProductId: smmProduct.id,
            targetId: target,
            quantity: qty,
            price: totalPrice,
            status: 'PAID',
            paymentMethod: 'BALANCE',
            paidAt: new Date(),
          }
        })

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

        return order.id
      })

      fulfillSmmOrder(result).catch(err => console.error('[SMM FULFILL FAIL]', err))

      return NextResponse.json({ message: 'Pembayaran berhasil, pesanan sedang diproses', success: true })
    }
    else if (method === 'QRIS') {
      const order = await prisma.order.create({
        data: {
          userId: user.id,
          productType: 'SMM',
          smmProductId: smmProduct.id,
          targetId: target,
          quantity: qty,
          price: totalPrice,
          status: 'PENDING',
          paymentMethod: 'QRIS',
        }
      })

      try {
        const qrisResult = await generateQris({
          amount: totalPrice,
          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: totalPrice,
            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 })
  }
}
