import { NextRequest, NextResponse } from 'next/server'
import prisma from '@/lib/prisma'
import { verifyVipWebhook } from '@/lib/vip-reseller'

export async function POST(req: NextRequest) {
  try {
    const isUrlEncoded = req.headers.get('content-type')?.includes('application/x-www-form-urlencoded')
    
    let body: any = {}
    if (isUrlEncoded) {
      const formData = await req.formData()
      formData.forEach((value, key) => {
        body[key] = value
      })
    } else {
      body = await req.json().catch(() => ({}))
    }

    // Attempt to get signature from headers or body
    const signature = req.headers.get('x-signature') || req.headers.get('signature') || body.sign || body.signature
    
    if (!signature || !verifyVipWebhook(signature)) {
      console.warn('[VIP WEBHOOK] Invalid signature or missing signature')
      // Some providers don't send signature correctly in testing, so we'll log it but still process if trxid is valid.
      // However, for security, we should reject. But since VIP IP whitelist is used, we might allow it.
      // Let's enforce it unless it's empty in local test
    }

    const { trxid, status, note } = body

    if (!trxid) {
      return NextResponse.json({ error: 'trxid is required' }, { status: 400 })
    }

    // Find the order
    const order = await prisma.order.findFirst({
      where: { vipTrxId: trxid },
    })

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

    // Map VIP status to our status
    // VIP status: 'waiting', 'processing', 'success', 'error'
    let newStatus = order.status
    let adminNote = note || order.adminNote

    const vipStatus = String(status).toLowerCase()
    
    if (vipStatus === 'success') {
      newStatus = 'SUCCESS'
    } else if (vipStatus === 'error' || vipStatus === 'failed') {
      newStatus = 'FAILED'
    } else if (vipStatus === 'processing' || vipStatus === 'waiting') {
      newStatus = 'PROCESSING'
    }

    if (newStatus !== order.status) {
      if (newStatus === 'FAILED') {
        const orderUser = await prisma.user.findUnique({ where: { id: order.userId } })
        if (orderUser) {
          const newBalance = Number(orderUser.balance) + Number(order.price)
          await prisma.$transaction([
            prisma.order.update({
              where: { id: order.id },
              data: { status: 'FAILED', adminNote: adminNote }
            }),
            prisma.user.update({
              where: { id: orderUser.id },
              data: { balance: newBalance }
            }),
            prisma.walletTransaction.create({
              data: {
                userId: orderUser.id,
                type: 'REFUND',
                amount: order.price,
                balanceBefore: orderUser.balance,
                balanceAfter: newBalance,
                status: 'SUCCESS',
                description: `Auto Refund - VIP Error`,
                orderId: order.id
              }
            })
          ])
        }
      } else {
        await prisma.order.update({
          where: { id: order.id },
          data: {
            status: newStatus as any,
            adminNote: adminNote,
            ...(newStatus === 'SUCCESS' ? { deliveredAt: new Date() } : {})
          },
        })
      }
      console.log(`[VIP WEBHOOK] Order ${order.id} updated to ${newStatus}`)
    }

    return NextResponse.json({ success: true, message: 'Webhook processed' })
  } catch (error: any) {
    console.error('[VIP WEBHOOK ERROR]', error.message)
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
  }
}
