import prisma from './prisma'
import { getPteroUserByEmail, createPteroUser, createPteroServer } from './pterodactyl'
import { notifyAccountDelivery } from './notifications'

export async function fulfillPteroOrder(serverId: string) {
  const serverRecord = await prisma.pterodactylServer.findUnique({
    where: { id: serverId },
    include: {
      user: true,
      package: true
    }
  })

  if (!serverRecord) throw new Error('Server record not found')
  if (serverRecord.status !== 'PENDING') return // Already processed

  let pteroUserId = serverRecord.pteroUserId
  let pteroUsername = serverRecord.pteroUsername
  let pteroPassword = serverRecord.pteroPassword

  try {
    // 1. Check or Create User in Pterodactyl
    if (!pteroUserId) {
      const existingUser = await getPteroUserByEmail(serverRecord.user.email)
      if (existingUser) {
        pteroUserId = existingUser.id
        pteroUsername = pteroUsername || existingUser.username
      } else {
        // Use user-provided credentials, fallback to auto-generated if somehow missing
        if (!pteroPassword) {
          pteroPassword = Math.random().toString(36).slice(-10) + Math.random().toString(36).slice(-4).toUpperCase()
        }
        const usernameClean = (pteroUsername || serverRecord.user.name.replace(/[^a-zA-Z0-9._-]/g, '').toLowerCase() || `user_${serverRecord.userId.slice(-6)}`).slice(0, 32)

        const pUser = await createPteroUser(
          serverRecord.user.email,
          usernameClean,
          serverRecord.user.name,
          'AmaneNime',
          pteroPassword
        )
        pteroUserId = pUser.id
        pteroUsername = pUser.username
      }
    }

    // 2. Create Server
    const serverName = `${serverRecord.package.name} - ${serverRecord.user.name}`
    const pServer = await createPteroServer({
      name: serverName.slice(0, 50),
      userId: pteroUserId,
      eggId: serverRecord.package.eggId,
      nestId: serverRecord.package.nestId,
      locationId: serverRecord.package.locationId,
      memory: serverRecord.package.memory,
      disk: serverRecord.package.disk,
      cpu: serverRecord.package.cpu,
      databases: serverRecord.package.databases,
      backups: serverRecord.package.backups,
      allocations: serverRecord.package.allocations,
      image: serverRecord.package.image,
      startup: serverRecord.package.startup || undefined
    })

    // 3. Calculate Expiry
    const expiresAt = new Date()
    expiresAt.setDate(expiresAt.getDate() + serverRecord.package.durationDays)

    // 4. Update Database
    await prisma.pterodactylServer.update({
      where: { id: serverId },
      data: {
        pteroUserId,
        pteroUsername,
        pteroPassword: pteroPassword || null,
        pteroServerId: pServer.id,
        pteroIdentifier: pServer.identifier,
        status: 'ACTIVE',
        expiresAt,
        lastRenewedAt: new Date()
      }
    })

    // 5. Send Email
    // Using existing template for digital products, but adapted for Pterodactyl
    const panelUrl = process.env.PTERODACTYL_URL || 'https://panel.example.com'
    await notifyAccountDelivery(serverRecord.user, {
      name: serverRecord.user.name,
      orderId: serverRecord.id,
      productName: `Hosting: ${serverRecord.package.name}`,
      email: pteroUsername || serverRecord.user.email,
      password: pteroPassword || '(Sudah pernah dibuat, gunakan password panel Anda)',
      extra: `Panel URL: ${panelUrl}\nServer Identifier: ${pServer.identifier}`
    })

    return { success: true, identifier: pServer.identifier }
  } catch (error: any) {
    console.error('[PTERO FULFILLMENT ERROR]', error)
    // Don't fail the transaction, leave it as PENDING and admin can retry
    throw error
  }
}
