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

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

  const servers = await prisma.pterodactylServer.findMany({
    include: {
      user: { select: { name: true, email: true } },
      package: { select: { name: true } }
    },
    orderBy: { createdAt: 'desc' }
  })
  
  return NextResponse.json(servers)
}

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, action } = await req.json()
  
  const pteroServer = await prisma.pterodactylServer.findUnique({ where: { id } })
  if (!pteroServer) return NextResponse.json({ error: 'Server tidak ditemukan' }, { status: 404 })

  try {
    if (action === 'suspend' && pteroServer.pteroServerId) {
      await suspendPteroServer(pteroServer.pteroServerId)
      await prisma.pterodactylServer.update({
        where: { id },
        data: { status: 'SUSPENDED' }
      })
    } else if (action === 'unsuspend' && pteroServer.pteroServerId) {
      await unsuspendPteroServer(pteroServer.pteroServerId)
      await prisma.pterodactylServer.update({
        where: { id },
        data: { status: 'ACTIVE' }
      })
    } else if (action === 'delete') {
      if (pteroServer.pteroServerId) {
        await deletePteroServer(pteroServer.pteroServerId)
      }
      await prisma.pterodactylServer.update({
        where: { id },
        data: { status: 'DELETED' }
      })
    } else {
      return NextResponse.json({ error: 'Action invalid' }, { status: 400 })
    }

    return NextResponse.json({ success: true })
  } catch (error: any) {
    return NextResponse.json({ error: error.message }, { status: 500 })
  }
}
