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

const router = express.Router();
import {
  listFilesRouteHandler,
  getFileRouteHandler,
  getFileContentRouteHandler,
  editFileRouteHandler,
  newFileRouteHandler,
  flushFileRouteHandler,
  deleteFileRouteHandler,
  listFilesByPropertiesRouteHandler,
  getFileStatsRouteHandler,
  getFileHistoryRouteHandler,
} from '../../services/management/files.js';

// list of files
router.get('/', isAuthenticated, (req, res) => {
  const { page, limit, property, search, sort, order } = req.query;
  const allowedFilters = ['_id', 'name', 'type', 'size'];
  const filter = getFilter(req.query, allowedFilters);
  listFilesRouteHandler(req, res, page, limit, property, filter, search, sort, order);
});

router.get('/properties', isAuthenticated, (req, res) => {
  let properties = convertPropertiesString(req.query.properties);
  const allowedFilters = ['type'];
  const filter = getFilter(req.query, allowedFilters, false);
  listFilesByPropertiesRouteHandler(req, res, properties, filter);
});

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

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

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

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

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

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

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

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

export default router;
