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

const router = express.Router();
import {
  listInvoicesRouteHandler,
  getInvoiceRouteHandler,
  editInvoiceRouteHandler,
  editMultipleInvoicesRouteHandler,
  newInvoiceRouteHandler,
  deleteInvoiceRouteHandler,
  listInvoicesByPropertiesRouteHandler,
  getInvoiceStatsRouteHandler,
  getInvoiceHistoryRouteHandler,
  sendInvoiceRouteHandler,
  markInvoicePaidRouteHandler,
  cancelInvoiceRouteHandler,
} from '../../services/finance/invoices.js';

// list of invoices
router.get('/', isAuthenticated, (req, res) => {
  const { page, limit, property, search, sort, order } = req.query;
  const allowedFilters = [
    'vendor',
    'customer',
    'invoiceType',
    'state',
    'value',
    'vendor._id',
    'customer._id',
  ];
  const filter = getFilter(req.query, allowedFilters);
  listInvoicesRouteHandler(req, res, page, limit, property, filter, search, sort, order);
});

router.get('/properties', isAuthenticated, (req, res) => {
  let properties = convertPropertiesString(req.query.properties);
  const allowedFilters = [
    'vendor',
    'customer',
    'invoiceType',
    'state.type',
    'value',
    'vendor._id',
    'customer._id',
  ];
  const filter = getFilter(req.query, allowedFilters, false);
  var masterFilter = {};
  if (req.query.masterFilter) {
    masterFilter = JSON.parse(req.query.masterFilter);
  }
  listInvoicesByPropertiesRouteHandler(req, res, properties, filter, masterFilter);
});

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

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

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

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

// update multiple invoices
router.put('/', isAuthenticated, async (req, res) => {
  editMultipleInvoicesRouteHandler(req, res);
});

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

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

router.post('/:id/send', isAuthenticated, async (req, res) => {
  sendInvoiceRouteHandler(req, res);
});

router.post('/:id/markpaid', isAuthenticated, async (req, res) => {
  markInvoicePaidRouteHandler(req, res);
});

router.post('/:id/cancel', isAuthenticated, async (req, res) => {
  cancelInvoiceRouteHandler(req, res);
});

export default router;
