import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import prisma from '@/lib/prisma'

export async function GET(req: NextRequest) {
  const session = await getServerSession(authOptions)
  if (session?.user?.role !== 'ADMIN') return NextResponse.json({ error: 'Forbidden' }, { status: 403 })

  const packages = await prisma.pterodactylPackage.findMany({
    orderBy: { sortOrder: 'asc' }
  })
  
  return NextResponse.json(packages)
}

export async function POST(req: NextRequest) {
  const session = await getServerSession(authOptions)
  if (session?.user?.role !== 'ADMIN') return NextResponse.json({ error: 'Forbidden' }, { status: 403 })

  const body = await req.json()
  const pkg = await prisma.pterodactylPackage.create({
    data: {
      name: body.name,
      description: body.description,
      price: body.price,
      durationDays: body.durationDays,
      memory: body.memory,
      disk: body.disk,
      cpu: body.cpu,
      databases: body.databases,
      backups: body.backups,
      allocations: body.allocations,
      eggId: body.eggId,
      nestId: body.nestId,
      locationId: body.locationId,
      image: body.image,
      startup: body.startup,
      isActive: body.isActive ?? true,
      sortOrder: body.sortOrder ?? 0,
    }
  })
  
  return NextResponse.json(pkg)
}

export async function PATCH(req: NextRequest) {
  const session = await getServerSession(authOptions)
  if (session?.user?.role !== 'ADMIN') return NextResponse.json({ error: 'Forbidden' }, { status: 403 })

  const { id, ...data } = await req.json()
  const pkg = await prisma.pterodactylPackage.update({
    where: { id },
    data
  })
  
  return NextResponse.json(pkg)
}

export async function DELETE(req: NextRequest) {
  const session = await getServerSession(authOptions)
  if (session?.user?.role !== 'ADMIN') return NextResponse.json({ error: 'Forbidden' }, { status: 403 })

  const { searchParams } = new URL(req.url)
  const id = searchParams.get('id')
  
  if (!id) return NextResponse.json({ error: 'Missing ID' }, { status: 400 })

  try {
    // Cek apakah ada server yang masih aktif pakai paket ini
    const activeServers = await prisma.pterodactylServer.count({
      where: { packageId: id }
    })

    if (activeServers > 0) {
      return NextResponse.json({ 
        error: `Gagal dihapus: Ada ${activeServers} server pelanggan yang masih memakai paket ini. Nonaktifkan saja jika tidak ingin dijual lagi.` 
      }, { status: 400 })
    }

    // Putuskan relasi dari Order jika ada yang pakai paket ini (karena pteroPackageId itu opsional)
    await prisma.order.updateMany({
      where: { pteroPackageId: id },
      data: { pteroPackageId: null }
    })

    await prisma.pterodactylPackage.delete({
      where: { id }
    })
    
    return NextResponse.json({ success: true })
  } catch (error: any) {
    return NextResponse.json({ error: error.message }, { status: 500 })
  }
}
