// ── System: Monitor ──────────────────────────────────────────────────────────
// GET /api/system/monitor  — Return basic system health metrics
//
// Auth: authenticated
// Returns: RSS memory (MB), CPU usage (% of one core), CPU core count
// CPU is calculated as process CPU time delta over wall clock time.

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

// Module-level state for CPU delta calculation
let prevCpu = process.cpuUsage()
let prevTime = Date.now()

// ── GET ──────────────────────────────────────────────────────────────────────

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

  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 (microseconds) / wall time (milliseconds * 1000) * 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,
  })
}
