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

const router = express.Router();
import {
  listCouriersRouteHandler,
  getCourierRouteHandler,
  editCourierRouteHandler,
  newCourierRouteHandler,
  deleteCourierRouteHandler,
  listCouriersByPropertiesRouteHandler,
  getCourierStatsRouteHandler,
  getCourierHistoryRouteHandler,
} from '../../services/management/courier.js';

// list of couriers
router.get('/', isAuthenticated, (req, res) => {
  const { page, limit, property, search, sort, order } = req.query;
  const allowedFilters = ['name', 'website', 'email', 'phone', 'contact', 'country'];
  const filter = getFilter(req.query, allowedFilters);
  listCouriersRouteHandler(req, res, page, limit, property, filter, search, sort, order);
});

router.get('/properties', isAuthenticated, (req, res) => {
  let properties = convertPropertiesString(req.query.properties);
  const allowedFilters = ['name', 'website', 'email', 'phone', 'contact', 'country'];
  const filter = getFilter(req.query, allowedFilters, false);
  listCouriersByPropertiesRouteHandler(req, res, properties, filter);
});

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

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

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

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

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

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

export default router;
