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

const router = express.Router();
import {
  listProductsRouteHandler,
  getProductRouteHandler,
  editProductRouteHandler,
  newProductRouteHandler,
  deleteProductRouteHandler,
  listProductsByPropertiesRouteHandler,
  getProductStatsRouteHandler,
  getProductHistoryRouteHandler,
} from '../../services/management/products.js';

// list of products
router.get('/', isAuthenticated, (req, res) => {
  const { page, limit, property, search, sort, order } = req.query;
  const allowedFilters = ['_id', 'name', 'globalPrice'];
  const filter = getFilter(req.query, allowedFilters);
  listProductsRouteHandler(req, res, page, limit, property, filter, search, sort, order);
});

router.get('/properties', isAuthenticated, (req, res) => {
  let properties = convertPropertiesString(req.query.properties);
  const allowedFilters = [];
  const filter = getFilter(req.query, allowedFilters, false);
  listProductsByPropertiesRouteHandler(req, res, properties, filter);
});

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

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

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

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

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

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

export default router;
