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

const router = express.Router();
import {
  listOrderItemsRouteHandler,
  getOrderItemRouteHandler,
  editOrderItemRouteHandler,
  newOrderItemRouteHandler,
  deleteOrderItemRouteHandler,
  listOrderItemsByPropertiesRouteHandler,
  getOrderItemStatsRouteHandler,
  getOrderItemHistoryRouteHandler,
} from '../../services/inventory/orderitems.js';

// list of order items
router.get('/', isAuthenticated, (req, res) => {
  const { page, limit, property, search, sort, order } = req.query;
  const allowedFilters = ['itemType', 'item', 'item._id', 'order', 'order._id', 'orderType'];
  const filter = getFilter(req.query, allowedFilters);
  listOrderItemsRouteHandler(req, res, page, limit, property, filter, search, sort, order);
});

router.get('/properties', isAuthenticated, (req, res) => {
  let properties = convertPropertiesString(req.query.properties);
  const allowedFilters = ['itemType', 'item', 'item._id', 'order', 'order._id', 'orderType'];
  const filter = getFilter(req.query, allowedFilters, false);
  var masterFilter = {};
  if (req.query.masterFilter) {
    masterFilter = JSON.parse(req.query.masterFilter);
  }
  listOrderItemsByPropertiesRouteHandler(req, res, properties, filter, masterFilter);
});

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

// get order item stats
router.get('/stats', isAuthenticated, (req, res) => {
  getOrderItemStatsRouteHandler(req, res);
});

// get order item history
router.get('/history', isAuthenticated, (req, res) => {
  getOrderItemHistoryRouteHandler(req, res);
});

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

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

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

export default router;
