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

const router = express.Router();
import {
  listHostsRouteHandler,
  getHostRouteHandler,
  editHostRouteHandler,
  newHostRouteHandler,
  deleteHostRouteHandler,
  listHostsByPropertiesRouteHandler,
  getHostStatsRouteHandler,
  getHostHistoryRouteHandler,
} from '../../services/management/hosts.js';

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

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

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

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

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

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

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

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

export default router;
