/* =====================================================================
   routes/audit.js — Aktivitätsprotokoll ansehen. 1:1 portiert aus
   cloudflare-worker/src/routes/audit.js.
   ===================================================================== */
import { db } from "../db.js";
import { hasPermission } from "../lib/permissions.js";
import { json } from "../lib/http.js";

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