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

const router = express.Router();
import {
  listDocumentTemplatesRouteHandler,
  getDocumentTemplateRouteHandler,
  editDocumentTemplateRouteHandler,
  newDocumentTemplateRouteHandler,
  deleteDocumentTemplateRouteHandler,
  listDocumentTemplatesByPropertiesRouteHandler,
  getDocumentTemplateStatsRouteHandler,
  getDocumentTemplateHistoryRouteHandler,
} from '../../services/management/documenttemplates.js';

// list of document templates
router.get('/', isAuthenticated, (req, res) => {
  const { page, limit, property, search, sort, order } = req.query;
  const allowedFilters = ['name', 'tags', 'active', 'global', 'objectType'];
  const filter = getFilter(req.query, allowedFilters);
  listDocumentTemplatesRouteHandler(req, res, page, limit, property, filter, search, sort, order);
});

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

router.post('/', isAuthenticated, (req, res) => {
  newDocumentTemplateRouteHandler(req, res);
});

// get document template stats
router.get('/stats', isAuthenticated, (req, res) => {
  getDocumentTemplateStatsRouteHandler(req, res);
});

// get document template history
router.get('/history', isAuthenticated, (req, res) => {
  getDocumentTemplateHistoryRouteHandler(req, res);
});

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

router.put('/:id', isAuthenticated, async (req, res) => {
  editDocumentTemplateRouteHandler(req, res);
});

router.delete('/:id', isAuthenticated, async (req, res) => {
  deleteDocumentTemplateRouteHandler(req, res);
});

export default router;
