import express from 'express';
import { isAuthenticated } from '../../keycloak.js';
import { convertPropertiesString, getFilter } from '../../utils.js';

const router = express.Router();
import {
  listUsersRouteHandler,
  listUsersByPropertiesRouteHandler,
  getUserRouteHandler,
  editUserRouteHandler,
  getUserStatsRouteHandler,
  getUserHistoryRouteHandler,
} from '../../services/management/users.js';

// list of document templates
router.get('/', isAuthenticated, (req, res) => {
  const { page, limit, property, search, sort, order } = req.query;
  const allowedFilters = ['name', 'username', 'firstName', 'lastName', 'email'];
  const filter = getFilter(req.query, allowedFilters);
  listUsersRouteHandler(req, res, page, limit, property, filter, search, sort, order);
});

router.get('/properties', isAuthenticated, (req, res) => {
  let properties = convertPropertiesString(req.query.properties);
  const allowedFilters = [];
  const filter = getFilter(req.query, allowedFilters, false);
  var masterFilter = {};
  if (req.query.masterFilter) {
    masterFilter = JSON.parse(req.query.masterFilter);
  }
  listUsersByPropertiesRouteHandler(req, res, properties, filter, masterFilter);
});

// get user stats
router.get('/stats', isAuthenticated, (req, res) => {
  getUserStatsRouteHandler(req, res);
});

// get user history
router.get('/history', isAuthenticated, (req, res) => {
  getUserHistoryRouteHandler(req, res);
});

router.get('/:id', isAuthenticated, (req, res) => {
  getUserRouteHandler(req, res);
});

// update user info
router.put('/:id', isAuthenticated, async (req, res) => {
  editUserRouteHandler(req, res);
});

export default router;
