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

const router = express.Router();
import {
  listTaxRatesRouteHandler,
  getTaxRateRouteHandler,
  editTaxRateRouteHandler,
  newTaxRateRouteHandler,
  deleteTaxRateRouteHandler,
  listTaxRatesByPropertiesRouteHandler,
  getTaxRateStatsRouteHandler,
  getTaxRateHistoryRouteHandler,
} from '../../services/management/taxrates.js';

// list of tax rates
router.get('/', isAuthenticated, (req, res) => {
  const { page, limit, property, search, sort, order } = req.query;
  const allowedFilters = ['name', 'rate', 'rateType', 'active', 'country'];
  const filter = getFilter(req.query, allowedFilters);
  listTaxRatesRouteHandler(req, res, page, limit, property, filter, search, sort, order);
});

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

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

// get tax rate stats
router.get('/stats', isAuthenticated, (req, res) => {
  getTaxRateStatsRouteHandler(req, res);
});

// get tax rate history
router.get('/history', isAuthenticated, (req, res) => {
  getTaxRateHistoryRouteHandler(req, res);
});

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

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

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

export default router;
