import prisma from './prisma'
import { placeZaynflazzOrder } from './zaynflazz'

export async function fulfillSmmOrder(orderId: string) {
  const order = await prisma.order.findUnique({
    where: { id: orderId },
    include: {
      smmProduct: true,
      user: true
    }
  })

  if (!order) throw new Error('Order not found')
  if (order.status !== 'PENDING' && order.status !== 'PAID') return // Only process PENDING or PAID

  if (!order.smmProduct) throw new Error('Not an SMM order')

  try {
    // Determine custom inputs if they were stored in `notes` or similar.
    // For now we assume `targetId` is the target link/username and `quantity` is jumlah.
    const target = order.targetId || ''
    const quantity = order.quantity

    if (!target) throw new Error('Target (Link/Username) is empty')

    const zaynflazzRes = await placeZaynflazzOrder(order.smmProduct.serviceId, target, quantity)
    
    // Update order to PROCESSING and store smmTrxId
    await prisma.order.update({
      where: { id: orderId },
      data: {
        status: 'PROCESSING',
        smmTrxId: zaynflazzRes.id
      }
    })

    return { success: true, trxId: zaynflazzRes.id }
  } catch (error: any) {
    console.error('[SMM FULFILLMENT ERROR]', error)
    
    // Mark as FAILED if rejected by Zaynflazz provider so admin can refund
    await prisma.order.update({
      where: { id: orderId },
      data: {
        status: 'FAILED',
        adminNote: `Zaynflazz Error: ${error.message}`
      }
    })

    // Note: We might want to handle refunds automatically here for Balance payments,
    // but typically manual refund is safer for SMM to avoid duplicate refund bugs.
    
    throw error
  }
}
