'use strict';

const express = require('express');
const router = express.Router();
const billingPrint = require('../modules/billing-print');
const { requirePermission } = require('../middleware/permissions');

router.use(requirePermission('billing.view'));

router.get('/status', (_req, res) => {
  res.json(billingPrint.bootstrap.buildStatus());
});

router.post('/restart', (_req, res) => {
  res.json(billingPrint.bootstrap.restartBillingPrint('api_billing_print_restart'));
});

router.get('/capture/status', (_req, res) => {
  res.json({ ok: true, ...billingPrint.bootstrap.ticketCapture.inspectTicketCapture() });
});

router.get('/capture/output-printers', (_req, res) => {
  res.json(billingPrint.bootstrap.ticketCapture.listOutputPrinters());
});

router.post('/capture/output-printer', express.json({ limit: '16kb' }), (req, res) => {
  const saved = billingPrint.bootstrap.ticketCapture.saveOutputPrinterName(req.body?.outputPrinterName || req.body?.printerName);
  if (!saved.ok) return res.status(400).json(saved);
  res.json({ ...saved, restart: billingPrint.bootstrap.restartBillingPrint('api_output_printer_saved') });
});

router.post('/capture/repair', (_req, res) => {
  const repair = billingPrint.bootstrap.ticketCapture.repairTicketCapture();
  const restart = repair.ok ? billingPrint.bootstrap.restartBillingPrint('api_capture_repair') : null;
  res.json({ ...repair, restart });
});

router.post('/capture/test-print', async (_req, res, next) => {
  try {
    res.json(await billingPrint.bootstrap.ticketCapture.testPrintTicketCapture());
  } catch (err) {
    next(err);
  }
});

router.post('/capture/softrestaurant-real-test/start', express.json({ limit: '32kb' }), async (req, res, next) => {
  try {
    res.json(await billingPrint.watcher.startSoftRestaurantRealTest(req.body || {}));
  } catch (err) {
    next(err);
  }
});

router.post('/test-ticket', async (req, res, next) => {
  try {
    res.json(await billingPrint.service.testTicket(req.body || {}));
  } catch (err) {
    next(err);
  }
});

module.exports = router;
