'use strict';

const express = require('express');
const fs = require('fs');
const path = require('path');
const router = express.Router();
const service = require('./billing-print.service');
const watcher = require('./billing-print.watcher');
const { STORE_FILE } = require('./billing-print.config');
const { requirePermission } = require('../../middleware/permissions');

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

router.get('/config', (req, res) => {
  res.json({ ok: true, config: service.getConfig() });
});

router.get('/status', (req, res) => {
  const bootstrap = require('./billing-print.bootstrap');
  res.json(bootstrap.buildStatus());
});

router.post('/logo', express.json({ limit: '3mb' }), (req, res, next) => {
  try {
    const rawName = String(req.body?.fileName || 'me-facturo-logo.png');
    const ext = path.extname(rawName).toLowerCase();
    if (!['.png', '.jpg', '.jpeg', '.webp', '.svg'].includes(ext)) {
      return res.status(400).json({ ok: false, error: 'Formato de logo no permitido' });
    }
    const base64 = String(req.body?.dataBase64 || '').split(',').pop();
    if (!base64) return res.status(400).json({ ok: false, error: 'Logo requerido' });
    const buffer = Buffer.from(base64, 'base64');
    if (!buffer.length || buffer.length > 2 * 1024 * 1024) {
      return res.status(400).json({ ok: false, error: 'Logo invalido o mayor a 2 MB' });
    }
    const dir = path.join(path.dirname(STORE_FILE), 'assets');
    fs.mkdirSync(dir, { recursive: true });
    const logoPath = path.join(dir, `me-facturo-logo${ext}`);
    fs.writeFileSync(logoPath, buffer);
    const config = service.saveConfig({ logoPath });
    res.json({ ok: true, config: service.publicConfig(config) });
  } catch (err) {
    next(err);
  }
});

router.post('/config', (req, res, next) => {
  try {
    const updates = req.body?.updates || req.body || {};
    const nextOutput = String(updates.outputPrinterName || updates.printerName || service.getConfig().outputPrinterName || service.getConfig().printerName || '').trim();
    const captureName = String(updates.capturePrinterName || service.getConfig().capturePrinterName || 'ARKHON Ticket Capture').trim();
    if (updates.enabled === true && !nextOutput) {
      return res.status(400).json({ ok: false, error: 'Seleccione outputPrinterName fisico antes de activar produccion.' });
    }
    if (nextOutput && nextOutput.toLowerCase() === captureName.toLowerCase()) {
      return res.status(400).json({ ok: false, error: 'outputPrinterName no puede ser ARKHON Ticket Capture.' });
    }
    const config = service.saveConfig(updates);
    const bootstrap = require('./billing-print.bootstrap');
    const restart = bootstrap.restartBillingPrint('admin_billing_print_config_saved');
    res.json({ ok: true, config: service.publicConfig(config), restart });
  } catch (err) {
    next(err);
  }
});

router.post('/process-next', async (req, res, next) => {
  try {
    res.json(await service.processNextPrn());
  } catch (err) {
    next(err);
  }
});

router.post('/restart', (req, res) => {
  const bootstrap = require('./billing-print.bootstrap');
  res.json(bootstrap.restartBillingPrint('admin_billing_print_restart'));
});

router.get('/capture/status', (req, res) => {
  const bootstrap = require('./billing-print.bootstrap');
  res.json({ ok: true, ...bootstrap.ticketCapture.inspectTicketCapture() });
});

router.get('/capture/output-printers', (req, res) => {
  const bootstrap = require('./billing-print.bootstrap');
  res.json(bootstrap.ticketCapture.listOutputPrinters());
});

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

router.post('/capture/repair', (req, res) => {
  const bootstrap = require('./billing-print.bootstrap');
  const repair = bootstrap.ticketCapture.repairTicketCapture();
  const restart = repair.ok ? bootstrap.restartBillingPrint('admin_capture_repair') : null;
  res.json({ ...repair, restart });
});

router.post('/capture/test-print', async (req, res, next) => {
  try {
    const bootstrap = require('./billing-print.bootstrap');
    res.json(await 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 watcher.startSoftRestaurantRealTest(req.body || {}));
  } catch (err) {
    next(err);
  }
});

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

module.exports = router;
