const express = require("express");
const {
  loadTemplate,
  saveTemplate,
  getDefaultTemplate,
  validateTemplate,
} = require("./receipt-template");
const {
  renderReceiptText,
  getSampleOrder,
} = require("./receipt-renderer");

function createTemplateRouter({ businessConfig } = {}) {
  const router = express.Router();
  const cfg = businessConfig || {};

  router.get("/api/receipt-template", (req, res) => {
    res.json(loadTemplate(cfg));
  });

  router.put("/api/receipt-template", (req, res) => {
    try {
      const saved = saveTemplate(req.body);
      res.json({ ok: true, template: saved });
    } catch (e) {
      res.status(400).json({ error: String(e.message || e) });
    }
  });

  router.post("/api/receipt-template/preview", (req, res) => {
    try {
      const template =
        req.body && req.body.template
          ? validateTemplate({
              ...getDefaultTemplate(cfg),
              ...req.body.template,
            })
          : loadTemplate(cfg);
      const order =
        req.body && req.body.order ? req.body.order : getSampleOrder();
      const previewText = renderReceiptText(template, order, {
        receiptKind: req.body?.receiptKind || "customer_receipt",
        businessConfig: cfg,
      });
      res.json({ previewText, template });
    } catch (e) {
      res.status(400).json({ error: String(e.message || e) });
    }
  });

  return router;
}

module.exports = { createTemplateRouter };
