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

const router = express.Router();
import {
  listVendorsRouteHandler,
  getVendorRouteHandler,
  editVendorRouteHandler,
  newVendorRouteHandler,
  deleteVendorRouteHandler,
  listVendorsByPropertiesRouteHandler,
  getVendorStatsRouteHandler,
  getVendorHistoryRouteHandler,
} from '../../services/management/vendors.js';

// list of vendors
router.get('/', isAuthenticated, (req, res) => {
  const { page, limit, property, search, sort, order } = req.query;
  const allowedFilters = ['country', 'active', 'createdAt', 'updatedAt'];
  const filter = getFilter(req.query, allowedFilters);
  listVendorsRouteHandler(req, res, page, limit, property, filter, search, sort, order);
});

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

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

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

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

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

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

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

export default router;
