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

const router = express.Router();
import {
  listShipmentsRouteHandler,
  getShipmentRouteHandler,
  editShipmentRouteHandler,
  newShipmentRouteHandler,
  deleteShipmentRouteHandler,
  listShipmentsByPropertiesRouteHandler,
  getShipmentStatsRouteHandler,
  getShipmentHistoryRouteHandler,
} from '../../services/inventory/shipments.js';

// list of shipments
router.get('/', isAuthenticated, (req, res) => {
  const { page, limit, property, search, sort, order } = req.query;
  const allowedFilters = [
    'vendor',
    'purchaseOrder',
    'state',
    'courierService',
    'vendor._id',
    'purchaseOrder._id',
  ];
  const filter = getFilter(req.query, allowedFilters);
  listShipmentsRouteHandler(req, res, page, limit, property, filter, search, sort, order);
});

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

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

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

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

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

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

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

export default router;
