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

const router = express.Router();
import {
  listPurchaseOrdersRouteHandler,
  getPurchaseOrderRouteHandler,
  editPurchaseOrderRouteHandler,
  newPurchaseOrderRouteHandler,
  deletePurchaseOrderRouteHandler,
  listPurchaseOrdersByPropertiesRouteHandler,
  getPurchaseOrderStatsRouteHandler,
  getPurchaseOrderHistoryRouteHandler,
} from '../../services/inventory/purchaseorders.js';

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

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

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

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

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

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

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

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

export default router;
