import { PrismaClient } from '@prisma/client'
import fetch from 'node-fetch'
import * as dotenv from 'dotenv'
import path from 'path'
import { checkZaynflazzOrderStatus } from '../lib/zaynflazz'
import { sendTelegramNotification } from '../lib/notifications' // You might need to update/ensure this exists

dotenv.config({ path: path.resolve(__dirname, '../.env.local') })
dotenv.config({ path: path.resolve(__dirname, '../.env') })

const prisma = new PrismaClient()

async function main() {
  console.log('[CRON] Checking SMM Zaynflazz pending orders...')
  
  const processingOrders = await prisma.order.findMany({
    where: {
      productType: 'SMM',
      status: 'PROCESSING',
      smmTrxId: { not: null }
    },
    include: { user: true, smmProduct: true }
  })

  for (const order of processingOrders) {
    if (!order.smmTrxId) continue

    console.log(`[CRON] Checking SMM Order ID: ${order.id} (TrxID: ${order.smmTrxId})`)
    
    try {
      const statusData = await checkZaynflazzOrderStatus(order.smmTrxId)
      const providerStatus = statusData.status.toLowerCase()
      // Zaynflazz typical statuses: Success, Completed, Processing, In Progress, Pending, Ditolak

      let newStatus: any = null

      if (['success', 'completed'].includes(providerStatus)) {
        newStatus = 'SUCCESS'
      } else if (['ditolak', 'canceled', 'error', 'failed', 'refunded'].includes(providerStatus)) {
        newStatus = 'FAILED'
      }

      if (newStatus) {
        await prisma.order.update({
          where: { id: order.id },
          data: { status: newStatus }
        })

        console.log(`[CRON] SMM Order ${order.id} updated to ${newStatus}`)

        // Optional: Send Notification to user (e.g., Telegram) if it's completed
        if (newStatus === 'SUCCESS' && order.user.telegramId) {
          const msg = `✅ <b>Pesanan SMM Selesai</b>\n\nPesanan <b>${order.smmProduct?.name}</b> untuk target ${order.targetId} telah berhasil diselesaikan.`
          await sendTelegramNotification(order.user.telegramId, msg).catch(() => {})
        } else if (newStatus === 'FAILED' && order.user.telegramId) {
          const msg = `❌ <b>Pesanan SMM Ditolak</b>\n\nPesanan <b>${order.smmProduct?.name}</b> Anda dibatalkan oleh provider. Silakan hubungi admin untuk pengembalian dana.`
          await sendTelegramNotification(order.user.telegramId, msg).catch(() => {})
        }
      }
    } catch (e: any) {
      console.error(`[CRON] Failed to check status for SMM order ${order.id}: ${e.message}`)
    }
  }

  console.log('[CRON] Done.')
}

main()
  .catch(console.error)
  .finally(() => prisma.$disconnect())
