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

const router = express.Router();
import {
  listPartStocksRouteHandler,
  getPartStockRouteHandler,
  editPartStockRouteHandler,
  newPartStockRouteHandler,
  deletePartStockRouteHandler,
  listPartStocksByPropertiesRouteHandler,
  getPartStockStatsRouteHandler,
  getPartStockHistoryRouteHandler,
} from '../../services/inventory/partstocks.js';

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

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

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

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

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

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

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

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

export default router;
