/* =====================================================================
   routes/audit.js — Aktivitätsprotokoll ansehen
   ===================================================================== */
import { hasPermission } from "../lib/permissions.js";
import { json } from "../lib/http.js";

export async function listAuditLog(request, env, session) {
  if (!session) return json({ ok: false, error: "Nicht angemeldet." }, 401);
  if (!session.isOwner && !hasPermission(session.permissions, session.overrides, "SETTINGS_VIEW_ACTIVITY_LOG")) {
    return json({ ok: false, error: "Keine Berechtigung." }, 403);
  }
  const body = await request.json().catch(() => ({}));
  const limit = Math.min(Number(body.limit) || 100, 500);
  const rows = await env.DB.prepare(
    `SELECT id, actor, action, target, detail, created_at FROM audit_log ORDER BY created_at DESC LIMIT ?`
  )
    .bind(limit)
    .all();
  return json({ ok: true, entries: rows.results || [] });
}
