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

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

// list of shipments
router.get('/', isAuthenticated, (req, res) => {
  const { page, limit, property, search, sort, order } = req.query;
  const allowedFilters = ['orderType', 'order', 'state', 'courierService', 'order._id', 'taxRate'];
  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 = [
    'orderType',
    'order',
    'state.type',
    'courierService',
    'order._id',
    'taxRate',
  ];
  const filter = getFilter(req.query, allowedFilters, false);
  var masterFilter = {};
  if (req.query.masterFilter) {
    masterFilter = getFilter(JSON.parse(req.query.masterFilter), allowedFilters, true);
  }
  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);
});

// update multiple shipments
router.put('/', isAuthenticated, async (req, res) => {
  editMultipleShipmentsRouteHandler(req, res);
});

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

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

router.post('/:id/ship', isAuthenticated, async (req, res) => {
  shipShipmentRouteHandler(req, res);
});

router.post('/:id/receive', isAuthenticated, async (req, res) => {
  receiveShipmentRouteHandler(req, res);
});

router.post('/:id/cancel', isAuthenticated, async (req, res) => {
  cancelShipmentRouteHandler(req, res);
});

export default router;
