import prisma from '@/lib/prisma'
import { checkCashifyStatus } from '@/lib/cashify'

export async function checkExpiredInvoices() {
  console.log('[CRON] Checking expired invoices...')
  try {
    // Find pending invoices older than 20 minutes
    const staleInvoices = await prisma.paymentInvoice.findMany({
      where: {
        status: 'pending',
        expiredAt: { lt: new Date() },
      },
      take: 50,
    })

    for (const invoice of staleInvoices) {
      try {
        // Double check with Cashify
        const status = await checkCashifyStatus(invoice.transactionId)
        
        if (status.status === 'paid' || status.status === 'success') {
          // Payment actually came in - process it
          await fetch(`${process.env.APP_URL}/api/payment/process`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ transactionId: invoice.transactionId, status: 'paid' }),
          })
        } else {
          // Mark as expired
          await prisma.paymentInvoice.update({
            where: { id: invoice.id },
            data: { status: 'expired' },
          })

          // Update related order
          if (invoice.orderId) {
            await prisma.order.updateMany({
              where: { id: invoice.orderId, status: 'PENDING' },
              data: { status: 'CANCELLED' },
            })
          }

          // Update wallet tx
          if (invoice.walletTxId) {
            await prisma.walletTransaction.updateMany({
              where: { id: invoice.walletTxId, status: 'PENDING' },
              data: { status: 'CANCELLED' },
            })
          }
        }
      } catch (err) {
        console.error(`[CRON] Failed to process invoice ${invoice.id}:`, err)
      }
    }

    console.log(`[CRON] Expired invoice check done: ${staleInvoices.length} processed`)
    return { processed: staleInvoices.length }
  } catch (error) {
    console.error('[CRON] Expired check failed:', error)
    throw error
  }
}
