import { NextRequest, NextResponse } from 'next/server'
import prisma from '@/lib/prisma'
import { createVipOrder } from '@/lib/vip-reseller'
import { notifyPaymentSuccess, notifyOrderSuccess, notifyOrderFailed, notifyAccountDelivery } from '@/lib/notifications'
import { sendH2HWebhook } from '@/lib/h2h-webhook'

import { checkCashifyStatus } from '@/lib/cashify'
import { eventEmitter } from '@/lib/event-emitter'

// This endpoint is called by Cashify when payment is confirmed
// Cashify uses polling-based detection, so we handle this from our own cron
// But also expose it as an internal webhook that can be called

export async function POST(req: NextRequest) {
  try {
    const body = await req.json()
    const { transactionId, status } = body

    if (!transactionId) {
      return NextResponse.json({ error: 'transactionId diperlukan' }, { status: 400 })
    }

    // Only process 'paid' or 'success' status
    if (status !== 'paid' && status !== 'success') {
      return NextResponse.json({ message: 'Status ignored' })
    }

    // VERIFY with Cashify before processing!
    // This prevents malicious users from bypassing payment
    try {
      const realStatus = await checkCashifyStatus(transactionId)
      if (realStatus.status !== 'paid' && realStatus.status !== 'success') {
        console.warn(`[PAYMENT PROCESS] Fraud attempt? ${transactionId} status is actually ${realStatus.status}`)
        return NextResponse.json({ error: 'Pembayaran belum lunas' }, { status: 400 })
      }
    } catch (e) {
      console.error('[PAYMENT PROCESS] Failed to verify with Cashify', e)
      return NextResponse.json({ error: 'Gagal memverifikasi status pembayaran' }, { status: 500 })
    }

    // Find the invoice
    const invoice = await prisma.paymentInvoice.findUnique({
      where: { transactionId },
    })

    if (!invoice || invoice.status === 'paid') {
      return NextResponse.json({ message: 'Already processed or not found' })
    }

    // Update invoice status
    await prisma.paymentInvoice.update({
      where: { transactionId },
      data: { status: 'paid', paidAt: new Date() },
    })

    const user = await prisma.user.findUnique({ where: { id: invoice.userId } })
    if (!user) return NextResponse.json({ error: 'User not found' }, { status: 404 })

    // ============================================
    // WALLET TOPUP FLOW
    // ============================================
    if (invoice.type === 'WALLET_TOPUP' && invoice.walletTxId) {
      const tx = await prisma.walletTransaction.findUnique({ where: { id: invoice.walletTxId } })
      if (!tx || tx.status === 'SUCCESS') {
        return NextResponse.json({ message: 'Already processed' })
      }

      const newBalance = Number(user.balance) + Number(invoice.amount)

      await prisma.$transaction([
        prisma.user.update({
          where: { id: user.id },
          data: { balance: newBalance },
        }),
        prisma.walletTransaction.update({
          where: { id: tx.id },
          data: {
            status: 'SUCCESS',
            balanceBefore: user.balance,
            balanceAfter: newBalance,
          },
        }),
      ])

      // Send notification
      await notifyPaymentSuccess(user, {
        name: user.name,
        amount: Number(invoice.amount),
        type: 'wallet',
        description: `Topup saldo berhasil`,
      })

      // Send H2H Webhook
      await sendH2HWebhook(user.id, {
        event: 'DEPOSIT_SUCCESS',
        transactionId: tx.id,
        amount: Number(invoice.amount),
        balance: newBalance
      })

      return NextResponse.json({ message: 'Wallet topup success' })
    }

    // ============================================
    // ORDER PAYMENT FLOW
    // ============================================
    if (invoice.type === 'ORDER_PAYMENT' && invoice.orderId) {
      const order = await prisma.order.findUnique({
        where: { id: invoice.orderId },
        include: {
          vipProduct: true,
          digitalProduct: true,
          smmProduct: true,
        },
      })

      if (!order || order.status !== 'PENDING') {
        return NextResponse.json({ message: 'Order already processed or not found' })
      }

      // Update order to PAID
      await prisma.order.update({
        where: { id: order.id },
        data: { status: 'PAID', paidAt: new Date() },
      })

      // ---- VIP ORDER ----
      let isFailed = false;
      if (order.productType === 'VIP' && order.vipProduct) {
        try {
          const vipResult = await createVipOrder({
            service: order.vipProduct.providerCode,
            dataNo: order.targetId!,
            dataZone: order.zone || undefined,
            additionalData: order.additionalData || undefined,
          })

          await prisma.order.update({
            where: { id: order.id },
            data: {
              status: 'PROCESSING',
              vipTrxId: vipResult.trxid,
            },
          })
        } catch (vipError: any) {
          isFailed = true;
          
          const currentUser = await prisma.user.findUnique({ where: { id: user.id } })
          const currentBalance = Number(currentUser?.balance || 0)
          const refundedBalance = currentBalance + Number(order.price)
          
          await prisma.$transaction([
            prisma.order.update({
              where: { id: order.id },
              data: { status: 'FAILED', adminNote: vipError.message },
            }),
            prisma.user.update({
              where: { id: user.id },
              data: { balance: refundedBalance },
            }),
            prisma.walletTransaction.create({
              data: {
                userId: user.id,
                type: 'REFUND',
                amount: order.price,
                balanceBefore: currentBalance,
                balanceAfter: refundedBalance,
                status: 'SUCCESS',
                description: `Auto Refund (QRIS) - VIP Error: ${vipError.message.slice(0, 30)}`,
                orderId: order.id,
              },
            }),
          ])
          console.error('[VIP ORDER FAILED]', vipError)
        }
      }

      // ---- DIGITAL PRODUCT ORDER ----
      if (order.productType === 'DIGITAL' && order.digitalProduct) {
        if (order.digitalProduct.type === 'AUTO') {
          // Find available account
          const account = await prisma.productAccount.findFirst({
            where: { productId: order.digitalProduct.id, status: 'AVAILABLE' },
          })

          if (account) {
            await prisma.$transaction([
              prisma.productAccount.update({
                where: { id: account.id },
                data: { status: 'SOLD', soldAt: new Date(), orderId: order.id },
              }),
              prisma.digitalProduct.update({
                where: { id: order.digitalProduct.id },
                data: { stock: { decrement: 1 } },
              }),
              prisma.order.update({
                where: { id: order.id },
                data: {
                  status: 'SUCCESS',
                  accountId: account.id,
                  deliveryData: { email: account.email, password: account.password, extra: account.extra },
                  deliveredAt: new Date(),
                },
              }),
            ])

            // Send account delivery email
            await notifyAccountDelivery(user, {
              name: user.name,
              orderId: order.id,
              productName: order.digitalProduct.name,
              email: account.email,
              password: account.password,
              extra: account.extra || undefined,
            })
          } else {
            // No stock - mark for manual delivery
            await prisma.order.update({
              where: { id: order.id },
              data: { status: 'PROCESSING', adminNote: 'Stok habis, perlu delivery manual' },
            })
          }
        } else {
          // MANUAL delivery - notify admin
          await prisma.order.update({
            where: { id: order.id },
            data: { status: 'PROCESSING' },
          })
        }
      }

      // ---- PTERODACTYL ORDER ----
      if (order.productType === 'PTERODACTYL' && order.pteroServerId) {
        await prisma.order.update({
          where: { id: order.id },
          data: { status: 'SUCCESS' }
        })

        if (order.notes === 'RENEWAL') {
          // This is a renewal order
          const pteroServer = await prisma.pterodactylServer.findUnique({
            where: { id: order.pteroServerId },
            include: { package: true }
          })

          if (pteroServer) {
            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 prisma.pterodactylServer.update({
              where: { id: pteroServer.id },
              data: {
                expiresAt: newExpiry,
                status: 'ACTIVE',
                lastRenewedAt: new Date(),
              }
            })

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

            if (pteroServer.status === 'SUSPENDED' && pteroServer.pteroServerId) {
              import('@/lib/pterodactyl').then(({ unsuspendPteroServer }) => {
                unsuspendPteroServer(pteroServer.pteroServerId!).catch(console.error)
              })
            }
          }
        } else {
          // This is a new server creation order
          import('@/lib/pterodactyl-fulfillment').then(({ fulfillPteroOrder }) => {
            fulfillPteroOrder(order.pteroServerId!).catch(console.error)
          })
        }
      }

      // ---- SMM ORDER ----
      if (order.productType === 'SMM' && order.smmProductId) {
        await prisma.order.update({
          where: { id: order.id },
          data: { status: 'PAID' }
        })
        // Trigger fulfillment async
        import('@/lib/zaynflazz-fulfillment').then(({ fulfillSmmOrder }) => {
          fulfillSmmOrder(order.id).catch(console.error)
        })
      }

      // Send order success email + SSE broadcast
      if (!isFailed) {
        const pName = order.vipProduct?.productName || order.digitalProduct?.name || (order.pteroPackageId ? 'Pterodactyl Server' : (order.smmProduct?.name || 'Produk'))
        await notifyOrderSuccess(user, {
          name: user.name,
          orderId: order.id,
          productName: pName,
          targetId: order.targetId || undefined,
          zone: order.zone || undefined,
          price: Number(order.price),
          isManual: order.digitalProduct?.type === 'MANUAL',
        })

        // 📡 Broadcast notifikasi ke semua pengunjung via SSE
        const firstName = user.name?.split(' ')[0] || 'Seseorang'
        eventEmitter.emit('purchase_success', {
          userName: firstName,
          productName: pName,
          time: new Date().toISOString(),
        })
        // H2H Webhook for order success
        await sendH2HWebhook(user.id, {
          event: 'ORDER_UPDATE',
          orderId: order.id,
          status: order.digitalProduct?.type === 'MANUAL' ? 'PROCESSING' : 'SUCCESS',
          note: 'Pembayaran diterima, pesanan sedang diproses',
          sn: null,
        })
      } else {
        // H2H Webhook for order failed
        await sendH2HWebhook(user.id, {
          event: 'ORDER_UPDATE',
          orderId: order.id,
          status: 'FAILED',
          note: 'Pesanan gagal diproses, saldo telah direfund',
          sn: null,
        })
      }
    }

    return NextResponse.json({ message: 'Payment processed successfully' })
  } catch (error) {
    console.error('[PAYMENT WEBHOOK]', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}
