import express from "express";
import { authenticate, requireMfa } from "../../middleware/auth.js";
import { requirePermission, requireRoles } from "../../middleware/rbac.js";
import { withDbSession } from "../../config/db.js";

const router = express.Router();
router.use(authenticate, requireMfa, requirePermission("system.audit", ["admin", "chair", "secretary"]));

router.get("/", async (req, res, next) => {
  try {
    const rows = await withDbSession(req.user, async (db) => {
      const result = await db.query(
        `SELECT id, actor_user_id, action, entity_type, entity_id, metadata, ip_address, created_at
           FROM audit_log
          ORDER BY created_at DESC
          LIMIT 500`
      );
      return result.rows;
    });
    res.json(rows);
  } catch (err) { next(err); }
});

export default router;
