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

const router = express.Router();
import {
  listFilamentStocksRouteHandler,
  getFilamentStockRouteHandler,
  editFilamentStockRouteHandler,
  newFilamentStockRouteHandler,
  deleteFilamentStockRouteHandler,
  listFilamentStocksByPropertiesRouteHandler,
  getFilamentStockStatsRouteHandler,
  getFilamentStockHistoryRouteHandler,
} from '../../services/inventory/filamentstocks.js';

// list of filament stocks
router.get('/', isAuthenticated, (req, res) => {
  const { page, limit, property, search, sort, order } = req.query;
  const allowedFilters = ['filament', 'state', 'startingWeight', 'currentWeight', 'filament._id'];
  const filter = getFilter(req.query, allowedFilters);
  listFilamentStocksRouteHandler(req, res, page, limit, property, filter, search, sort, order);
});

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

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

// get filament stock stats
router.get('/stats', isAuthenticated, (req, res) => {
  getFilamentStockStatsRouteHandler(req, res);
});

// get filament stock history
router.get('/history', isAuthenticated, (req, res) => {
  getFilamentStockHistoryRouteHandler(req, res);
});

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

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

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

export default router;
