import express from 'express';
import { isAuthenticated } from '../../keycloak.js';
import { parseFilter } from '../../utils.js';

const router = express.Router();
import {
  listMaterialsRouteHandler,
  getMaterialRouteHandler,
  editMaterialRouteHandler,
  newMaterialRouteHandler,
  getMaterialStatsRouteHandler,
  getMaterialHistoryRouteHandler,
} from '../../services/management/materials.js';

// list of materials
router.get('/', isAuthenticated, (req, res) => {
  const { page, limit, property } = req.query;

  const allowedFilters = ['type', 'brand', 'diameter', 'color'];

  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 };
      }
    }
  }

  listMaterialsRouteHandler(req, res, page, limit, property, filter);
});

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

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

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

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

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

export default router;
