import { NextRequest, NextResponse } from 'next/server'
import { authenticateH2H, h2hUnauthorized } from '@/lib/h2h-auth'
import prisma from '@/lib/prisma'
import { createVipOrder } from '@/lib/vip-reseller'
import { sendAccountDeliveryEmail } from '@/lib/email'

export const dynamic = 'force-dynamic'

export async function POST(req: NextRequest) {
  const h2hUser = await authenticateH2H(req)
  if (!h2hUser) return h2hUnauthorized()

  try {
    const body = await req.json()
    const { productType, productId, targetId, zone, additionalData } = body

    if (!productType || !productId) {
      return NextResponse.json({ success: false, error: 'productType dan productId diperlukan' }, { status: 400 })
    }

    let price = 0
    let productName = ''
    let vipProduct = null
    let digitalProduct = null

    if (productType === 'VIP') {
      vipProduct = await prisma.vipProduct.findUnique({ where: { id: productId, isActive: true, status: true } })
      if (!vipProduct) return NextResponse.json({ success: false, error: 'Produk VIP tidak ditemukan' }, { status: 404 })
      if (!targetId) return NextResponse.json({ success: false, error: 'targetId diperlukan untuk produk VIP' }, { status: 400 })
      price = Number(vipProduct.sellPrice)
      productName = `${vipProduct.gameName} - ${vipProduct.productName}`
    } else if (productType === 'DIGITAL') {
      digitalProduct = await prisma.digitalProduct.findUnique({ where: { id: productId, isActive: true } })
      if (!digitalProduct) return NextResponse.json({ success: false, error: 'Produk digital tidak ditemukan' }, { status: 404 })
      if (digitalProduct.stock < 1) return NextResponse.json({ success: false, error: 'Stok habis' }, { status: 400 })
      price = Number(digitalProduct.price)
      productName = digitalProduct.name
    } else {
      return NextResponse.json({ success: false, error: 'productType harus VIP atau DIGITAL' }, { status: 400 })
    }

    // Check balance
    const user = await prisma.user.findUnique({ where: { id: h2hUser.id } })
    if (!user || Number(user.balance) < price) {
      return NextResponse.json({ success: false, error: 'Saldo tidak mencukupi' }, { status: 400 })
    }

    const newBalance = Number(user.balance) - price

    const [order] = await prisma.$transaction([
      prisma.order.create({
        data: {
          userId: h2hUser.id,
          productType: productType as any,
          vipProductId: productType === 'VIP' ? productId : null,
          digitalProductId: productType === 'DIGITAL' ? productId : null,
          targetId: targetId || null,
          zone: zone || null,
          additionalData: additionalData || null,
          price,
          totalAmount: price,
          status: 'PAID',
          paymentMethod: 'h2h',
          paidAt: new Date(),
        },
      }),
      prisma.user.update({ where: { id: user.id }, data: { balance: newBalance } }),
      prisma.walletTransaction.create({
        data: {
          userId: user.id,
          type: 'PAYMENT',
          amount: price,
          balanceBefore: user.balance,
          balanceAfter: newBalance,
          status: 'SUCCESS',
          description: `[H2H] ${productName}`,
        },
      }),
    ])

    // Process fulfillment
    let fulfillmentStatus = 'PROCESSING'
    let deliveryData = null

    if (productType === 'VIP' && vipProduct) {
      try {
        const vipResult = await createVipOrder({
          service: vipProduct.providerCode,
          dataNo: targetId!,
          dataZone: zone || undefined,
          additionalData: additionalData || undefined,
        })
        await prisma.order.update({ where: { id: order.id }, data: { status: 'PROCESSING', vipTrxId: vipResult.trxid } })
        fulfillmentStatus = 'PROCESSING'
      } catch (e: any) {
        await prisma.$transaction([
          prisma.order.update({ where: { id: order.id }, data: { status: 'FAILED', adminNote: e.message } }),
          prisma.user.update({ where: { id: user.id }, data: { balance: Number(user.balance) } }),
          prisma.walletTransaction.create({
            data: {
              userId: user.id, type: 'REFUND', amount: price,
              balanceBefore: newBalance, balanceAfter: Number(user.balance),
              status: 'SUCCESS', description: `[H2H] Auto Refund: ${e.message?.slice(0, 40)}`,
              orderId: order.id,
            },
          }),
        ])
        return NextResponse.json({ success: false, error: `Order gagal: ${e.message}` }, { status: 500 })
      }
    } else if (productType === 'DIGITAL' && digitalProduct) {
      if (digitalProduct.type === 'AUTO') {
        const account = await prisma.productAccount.findFirst({ where: { productId: 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: 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() } }),
          ])
          fulfillmentStatus = 'SUCCESS'
          deliveryData = { email: account.email, password: account.password, extra: account.extra }
        }
      }
    }

    return NextResponse.json({
      success: true,
      data: {
        orderId: order.id,
        productName,
        price,
        status: fulfillmentStatus,
        deliveryData,
      },
    })
  } catch (error: any) {
    console.error('[H2H ORDER]', error)
    return NextResponse.json({ success: false, error: error.message || 'Internal error' }, { status: 500 })
  }
}

export async function GET(req: NextRequest) {
  const h2hUser = await authenticateH2H(req)
  if (!h2hUser) return h2hUnauthorized()

  try {
    const { searchParams } = new URL(req.url)
    const page = parseInt(searchParams.get('page') || '1')
    const limit = Math.min(parseInt(searchParams.get('limit') || '10'), 50)
    const skip = (page - 1) * limit

    const orders = await prisma.order.findMany({
      where: { userId: h2hUser.id, paymentMethod: 'h2h' },
      select: { id: true, productType: true, price: true, status: true, targetId: true, createdAt: true, vipProduct: { select: { gameName: true, productName: true } }, digitalProduct: { select: { name: true } } },
      orderBy: { createdAt: 'desc' },
      skip,
      take: limit,
    })

    return NextResponse.json({ success: true, data: orders })
  } catch (error) {
    return NextResponse.json({ success: false, error: 'Gagal memuat order' }, { status: 500 })
  }
}
