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

const router = express.Router();
import {
  listPartsRouteHandler,
  getPartRouteHandler,
  editPartRouteHandler,
  newPartRouteHandler,
  deletePartRouteHandler,
  listPartsByPropertiesRouteHandler,
  getPartStatsRouteHandler,
  getPartHistoryRouteHandler,
} from '../../services/management/parts.js';

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

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

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

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

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

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

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

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

export default router;
