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

const router = express.Router();
import {
  listStockEventsRouteHandler,
  getStockEventRouteHandler,
  newStockEventRouteHandler,
  editStockEventRouteHandler,
  deleteStockEventRouteHandler,
  listStockEventsByPropertiesRouteHandler,
  getStockEventStatsRouteHandler,
  getStockEventHistoryRouteHandler,
} from '../../services/inventory/stockevents.js';

// list of stock events
router.get('/', isAuthenticated, (req, res) => {
  const { page, limit, sort, order } = req.query;
  const allowedFilters = ['owner._id', 'parent._id'];
  const filter = getFilter(req.query, allowedFilters);
  listStockEventsRouteHandler(req, res, page, limit, filter, sort, order);
});

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

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

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

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

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

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

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

export default router;
