import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import prisma from '@/lib/prisma'
import { authOptions } from '@/lib/auth'
import { createVipOrder } from '@/lib/vip-reseller'
import { sendAccountDeliveryEmail } from '@/lib/email'
import { sendH2HWebhook } from '@/lib/h2h-webhook'

export async function GET(req: NextRequest) {
  const session = await getServerSession(authOptions)
  if (session?.user?.role !== 'ADMIN') return NextResponse.json({ error: 'Forbidden' }, { status: 403 })

  const { searchParams } = new URL(req.url)
  const page = parseInt(searchParams.get('page') || '1')
  const limit = parseInt(searchParams.get('limit') || '20')
  const status = searchParams.get('status') || undefined
  const search = searchParams.get('search') || ''
  const skip = (page - 1) * limit

  const [orders, total] = await Promise.all([
    prisma.order.findMany({
      where: {
        ...(status && { status: status as any }),
        ...(search && {
          OR: [
            { id: { contains: search } },
            { targetId: { contains: search } },
            { user: { email: { contains: search } } },
          ],
        }),
      },
      include: {
        user: { select: { name: true, email: true } },
        vipProduct: { select: { gameName: true, productName: true } },
        digitalProduct: { select: { name: true } },
        smmProduct: { select: { name: true } },
      },
      orderBy: { createdAt: 'desc' },
      skip,
      take: limit,
    }),
    prisma.order.count({ where: { ...(status && { status: status as any }) } }),
  ])

  return NextResponse.json({ orders, total, page, limit, pages: Math.ceil(total / limit) })
}

// PATCH - Update order status / manual deliver
export async function PATCH(
  req: NextRequest,
  { params }: { params: { id?: string } }
) {
  const session = await getServerSession(authOptions)
  if (session?.user?.role !== 'ADMIN') return NextResponse.json({ error: 'Forbidden' }, { status: 403 })

  const { searchParams } = new URL(req.url)
  const orderId = searchParams.get('id') || ''
  const action = searchParams.get('action') || ''
  const body = await req.json()

  const order = await prisma.order.findUnique({
    where: { id: orderId },
    include: { vipProduct: true, digitalProduct: true, user: true },
  })
  if (!order) return NextResponse.json({ error: 'Order tidak ditemukan' }, { status: 404 })

  // RETRY VIP order
  if (action === 'retry-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: orderId },
        data: { status: 'PROCESSING', vipTrxId: vipResult.trxid, retryCount: { increment: 1 } },
      })
      return NextResponse.json({ message: 'Retry berhasil' })
    } catch (error: any) {
      return NextResponse.json({ error: error.message }, { status: 400 })
    }
  }

  // MANUAL DELIVER digital account
  if (action === 'manual-deliver' && order.digitalProduct) {
    const { email, password, extra } = body
    await prisma.order.update({
      where: { id: orderId },
      data: {
        status: 'SUCCESS',
        deliveryData: { email, password, extra },
        deliveredAt: new Date(),
        adminNote: `Manual delivery by admin`,
      },
    })

    await sendAccountDeliveryEmail(order.user.email, {
      name: order.user.name,
      orderId: order.id,
      productName: order.digitalProduct.name,
      email,
      password,
      extra,
    }).catch(console.error)

    // H2H Webhook: notify reseller/user that order is fulfilled
    await sendH2HWebhook(order.userId, {
      event: 'ORDER_UPDATE',
      orderId: order.id,
      status: 'SUCCESS',
      note: 'Pesanan telah dikirim oleh admin',
      sn: extra || null,
    })

    return NextResponse.json({ message: 'Delivery berhasil' })
  }

  // UPDATE STATUS
  if (body.status) {
    if (body.status === 'REFUNDED' && order.status !== 'REFUNDED') {
      // Refund balance
      const newBalance = Number(order.user.balance) + Number(order.price)
      await prisma.$transaction([
        prisma.order.update({
          where: { id: orderId },
          data: { status: 'REFUNDED', adminNote: body.adminNote },
        }),
        prisma.user.update({
          where: { id: order.user.id },
          data: { balance: newBalance },
        }),
        prisma.walletTransaction.create({
          data: {
            userId: order.user.id,
            type: 'REFUND',
            amount: order.price,
            balanceBefore: order.user.balance,
            balanceAfter: newBalance,
            description: `Refund Order #${order.id.slice(-8).toUpperCase()}`,
            status: 'SUCCESS',
            orderId: order.id,
          },
        }),
      ])
    } else {
      await prisma.order.update({
        where: { id: orderId },
        data: { status: body.status, adminNote: body.adminNote },
      })
    }

    // H2H Webhook for status update
    if (['SUCCESS', 'FAILED', 'REFUNDED'].includes(body.status)) {
      await sendH2HWebhook(order.userId, {
        event: 'ORDER_UPDATE',
        orderId: order.id,
        status: body.status,
        note: body.adminNote || `Status diubah menjadi ${body.status}`,
        sn: null,
      })
    }

    return NextResponse.json({ message: 'Status diperbarui' })
  }

  return NextResponse.json({ error: 'Action tidak valid' }, { status: 400 })
}
