import { NextResponse } from "next/server"
import os from "os"
import { getSessionUser } from "@/lib/auth"

let prevCpu = process.cpuUsage()
let prevTime = Date.now()

export async function GET() {
  const sessionUser = await getSessionUser()
  if (!sessionUser) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
  if (sessionUser.role !== "admin" && sessionUser.role !== "super_admin") {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 })
  }

  const now = Date.now()
  const elapsed = now - prevTime
  const currentCpu = process.cpuUsage()

  const user = currentCpu.user - prevCpu.user
  const sys = currentCpu.system - prevCpu.system
  const totalUs = user + sys

  // CPU time (ms) / wall time (ms) * 100 = % of one core
  const cpuPct = elapsed > 0 ? Math.round((totalUs / 1000) / elapsed * 100 * 10) / 10 : 0

  prevCpu = currentCpu
  prevTime = now

  const mem = process.memoryUsage()

  return NextResponse.json({
    rssMB: Math.round(mem.rss / 1024 / 1024),
    cpuPct,
    cores: os.cpus().length,
  })
}
