import prisma from '@/lib/prisma'
import { checkVipOrderStatus } from '@/lib/vip-reseller'

export async function checkVipOrders() {
  console.log('[CRON] Checking VIP order statuses...')
  try {
    // Find all PROCESSING orders with a VIP trx ID
    const orders = await prisma.order.findMany({
      where: {
        status: 'PROCESSING',
        productType: 'VIP',
        vipTrxId: { not: null },
      },
      take: 50,
    })

    if (orders.length === 0) return { checked: 0 }

    let successCount = 0, failCount = 0

    for (const order of orders) {
      try {
        const vipStatus = await checkVipOrderStatus(order.vipTrxId!)
        
        if (vipStatus.status === 'success') {
          await prisma.order.update({
            where: { id: order.id },
            data: { status: 'SUCCESS', deliveredAt: new Date() },
          })
          successCount++
        } else if (vipStatus.status === 'error') {
          await prisma.order.update({
            where: { id: order.id },
            data: { status: 'FAILED', adminNote: vipStatus.note || 'VIP order failed' },
          })
          failCount++
        }
        // 'waiting' and 'processing' - keep checking
      } catch (err) {
        console.error(`[CRON] Failed to check order ${order.id}:`, err)
      }
    }

    console.log(`[CRON] VIP orders checked: ${successCount} success, ${failCount} failed`)
    return { checked: orders.length, successCount, failCount }
  } catch (error) {
    console.error('[CRON] Order check failed:', error)
    throw error
  }
}
