'use strict';

const express = require('express');
const service = require('./sync-monitor.service');
const billingPrint = require('../billing-print');

const router = express.Router();

function asyncRoute(fn) {
  return (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
}

router.get('/summary', asyncRoute(async (req, res) => res.json(await service.summary({
  includeDiagnostics: String(req.query?.details || '') === '1',
}))));
router.get('/events', asyncRoute(async (req, res) => res.json(await service.events(req.query || {}))));
router.get('/preview/:entityType', asyncRoute(async (req, res) => {
  res.json(await service.preview(String(req.params.entityType || ''), req.query.limit));
}));
router.post('/actions/retry', asyncRoute(async (req, res) => {
  const target = String(req.body?.target || 'all');
  if (!['all', 'operational', 'offline_first'].includes(target)) {
    return res.status(400).json({ ok: false, error: 'Objetivo de reintento no permitido' });
  }
  res.json(await service.retryQueues(target));
}));

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

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

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

router.post('/billing/test-print', asyncRoute(async (_req, res) => {
  const result = await billingPrint.bootstrap.ticketCapture.testPrintTicketCapture();
  res.status(result.ok ? 200 : 409).json(result);
}));

module.exports = router;
