import { PrismaClient } from '@prisma/client'
import fetch from 'node-fetch'
import * as dotenv from 'dotenv'
import path from 'path'
import { suspendPteroServer } from '../lib/pterodactyl'
import { sendTelegramNotification } from '../lib/notifications'

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 Pterodactyl server expiries...')
  
  const now = new Date()
  
  // 1. Suspend expired servers
  const expiredServers = await prisma.pterodactylServer.findMany({
    where: {
      status: 'ACTIVE',
      expiresAt: { lte: now }
    },
    include: { user: true, package: true }
  })

  for (const server of expiredServers) {
    console.log(`[CRON] Suspending expired server ID: ${server.id} (User: ${server.user.name})`)
    try {
      if (server.pteroServerId) {
        await suspendPteroServer(server.pteroServerId)
      }
      
      await prisma.pterodactylServer.update({
        where: { id: server.id },
        data: { status: 'SUSPENDED' }
      })

      // Notify User
      if (server.user.telegramId) {
        const msg = `⚠️ <b>Server Suspended</b>\n\nServer <b>${server.package.name}</b> Anda telah ditangguhkan karena masa aktif telah habis. Silakan perpanjang melalui dashboard.`
        await sendTelegramNotification(server.user.telegramId, msg)
      }

    } catch (e: any) {
      console.error(`[CRON] Failed to suspend server ${server.id}: ${e.message}`)
    }
  }

  // 2. Send 3-day reminder for active servers
  const threeDaysFromNow = new Date()
  threeDaysFromNow.setDate(now.getDate() + 3)

  const remindServers = await prisma.pterodactylServer.findMany({
    where: {
      status: 'ACTIVE',
      expiresAt: { lte: threeDaysFromNow, gt: now },
      OR: [
        { reminderSentAt: null },
        { reminderSentAt: { lt: new Date(now.getTime() - 24 * 60 * 60 * 1000) } } // Only send once a day
      ]
    },
    include: { user: true, package: true }
  })

  for (const server of remindServers) {
    console.log(`[CRON] Sending reminder for server ID: ${server.id}`)
    try {
      // Notify User
      if (server.user.telegramId) {
        const daysLeft = server.expiresAt ? Math.ceil((server.expiresAt.getTime() - now.getTime()) / (1000 * 3600 * 24)) : 0
        const msg = `⏰ <b>Reminder Perpanjangan</b>\n\nServer <b>${server.package.name}</b> Anda akan expired dalam ${daysLeft} hari. Segera perpanjang agar tidak di-suspend.`
        await sendTelegramNotification(server.user.telegramId, msg)
      }

      await prisma.pterodactylServer.update({
        where: { id: server.id },
        data: { reminderSentAt: now }
      })
    } catch (e: any) {
      console.error(`[CRON] Failed to send reminder for server ${server.id}: ${e.message}`)
    }
  }

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

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