const express = require("express");
const crypto = require("crypto");
const {
  listTemplates,
  loadTemplateById,
  saveTemplateById,
  deleteTemplateById,
  cloneTemplate,
  setDefaultForKind,
  validateTemplate,
  RECEIPT_KINDS,
} = require("./index");
const { normalizePosPayload } = require("../pos-payload");
const {
  renderReceiptText,
  buildReceiptPreviewModel,
  getSampleOrder,
} = require("../receipt-renderer");

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

  router.get("/api/templates", (req, res) => {
    res.json(listTemplates());
  });

  router.get("/api/templates/:id", (req, res) => {
    const t = loadTemplateById(req.params.id);
    if (!t) return res.status(404).json({ error: "NOT_FOUND" });
    res.json(t);
  });

  router.post("/api/templates", (req, res) => {
    try {
      const body = req.body || {};
      if (!body.id) {
        body.id = `tpl-${Date.now()}-${crypto.randomBytes(3).toString("hex")}`;
      }
      const saved = saveTemplateById(validateTemplate(body));
      res.status(201).json(saved);
    } catch (e) {
      res.status(e.status || 400).json({ error: String(e.message || e) });
    }
  });

  router.put("/api/templates/:id", (req, res) => {
    try {
      const body = { ...req.body, id: req.params.id };
      const saved = saveTemplateById(validateTemplate(body));
      res.json(saved);
    } catch (e) {
      res.status(e.status || 400).json({ error: String(e.message || e) });
    }
  });

  router.delete("/api/templates/:id", (req, res) => {
    try {
      deleteTemplateById(req.params.id);
      res.json({ ok: true });
    } catch (e) {
      res.status(e.status || 400).json({ error: String(e.message || e) });
    }
  });

  router.post("/api/templates/:id/clone", (req, res) => {
    try {
      const newId =
        req.body?.id ||
        `${req.params.id}-copy-${crypto.randomBytes(3).toString("hex")}`;
      const saved = cloneTemplate(req.params.id, newId, req.body?.name);
      res.status(201).json(saved);
    } catch (e) {
      res.status(e.status || 400).json({ error: String(e.message || e) });
    }
  });

  router.put("/api/templates/default/:receiptKind", (req, res) => {
    try {
      if (!RECEIPT_KINDS.includes(req.params.receiptKind)) {
        return res.status(400).json({ error: "INVALID_RECEIPT_KIND" });
      }
      const templateId = req.body?.templateId;
      if (!templateId) return res.status(400).json({ error: "templateId required" });
      const manifest = setDefaultForKind(req.params.receiptKind, templateId);
      res.json(manifest);
    } catch (e) {
      res.status(e.status || 400).json({ error: String(e.message || e) });
    }
  });

  router.post("/api/templates/:id/preview", (req, res) => {
    try {
      const template =
        req.body?.template || loadTemplateById(req.params.id);
      if (!template) return res.status(404).json({ error: "NOT_FOUND" });
      const order = normalizePosPayload(req.body?.order || getSampleOrder(), cfg);
      const previewOpts = {
        receiptKind: req.body?.receiptKind || template.receiptKind,
        businessConfig: cfg,
      };
      const previewText = renderReceiptText(template, order, previewOpts);
      const previewModel = buildReceiptPreviewModel(template, order, previewOpts);
      res.json({ previewText, previewModel, template });
    } catch (e) {
      res.status(400).json({ error: String(e.message || e) });
    }
  });

  return router;
}

module.exports = { createTemplateV2Router };
