import express from 'express';
import { isAuthenticated } from '../../keycloak.js';
import {
  listAuditLogsRouteHandler,
  getAuditLogRouteHandler,
  getAuditLogStatsRouteHandler,
  getAuditLogHistoryRouteHandler,
} from '../../services/management/auditlogs.js';
import { parseFilter } from '../../utils.js';

const router = express.Router();

// List note types
router.get('/', isAuthenticated, async (req, res) => {
  const { page, limit, sort, order } = req.query;

  const allowedFilters = ['parent._id', 'owner._id'];

  var filter = {};

  for (const [key, value] of Object.entries(req.query)) {
    for (var i = 0; i < allowedFilters.length; i++) {
      if (key == allowedFilters[i]) {
        const parsedFilter = parseFilter(key, value);
        filter = { ...filter, ...parsedFilter };
      }
    }
  }
  listAuditLogsRouteHandler(req, res, page, limit, filter, sort, order);
});

// get audit log stats
router.get('/stats', isAuthenticated, (req, res) => {
  getAuditLogStatsRouteHandler(req, res);
});

// get audit log history
router.get('/history', isAuthenticated, (req, res) => {
  getAuditLogHistoryRouteHandler(req, res);
});

/**
 * @route GET /api/auditlogs/:id
 * @desc Get a single audit log by ID
 * @access Private
 */
router.get('/:id', async (req, res) => {
  await getAuditLogRouteHandler(req, res);
});

export default router;
