import express from 'express';
import { isAuthenticated } from '../../keycloak.js';
import { parseFilter } from '../../utils.js';

const router = express.Router();
import {
  listStockAuditsRouteHandler,
  getStockAuditRouteHandler,
  newStockAuditRouteHandler,
  updateStockAuditRouteHandler,
  deleteStockAuditRouteHandler,
  getStockAuditStatsRouteHandler,
  getStockAuditHistoryRouteHandler,
} from '../../services/inventory/stockaudits.js';

// List stock audits
router.get('/', isAuthenticated, (req, res) => {
  const { page, limit, property } = req.query;

  const allowedFilters = ['status', 'type', 'createdBy'];

  var filter = {};

  for (const [key, value] of Object.entries(req.query)) {
    for (var i = 0; i < allowedFilters.length; i++) {
      if (key == allowedFilters[i]) {
        const parsedFilter = parseFilter(key, value);
        filter = { ...filter, ...parsedFilter };
      }
    }
  }

  listStockAuditsRouteHandler(req, res, page, limit, property, filter);
});

// Create new stock audit
router.post('/', isAuthenticated, (req, res) => {
  newStockAuditRouteHandler(req, res);
});

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

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

// Get specific stock audit
router.get('/:id', isAuthenticated, (req, res) => {
  getStockAuditRouteHandler(req, res);
});

// Update stock audit
router.put('/:id', isAuthenticated, (req, res) => {
  updateStockAuditRouteHandler(req, res);
});

// Delete stock audit
router.delete('/:id', isAuthenticated, (req, res) => {
  deleteStockAuditRouteHandler(req, res);
});

export default router;
