const { test } = require("node:test");
const assert = require("node:assert/strict");
const path = require("path");
const fs = require("fs");
const os = require("os");
const {
  initializeTemplates,
  loadTemplateById,
  cloneTemplate,
  resolveTemplateForJob,
  validateTemplate,
} = require("../lib/template-engine-v2");

test("template engine v2 initializes defaults", () => {
  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "siraya-tpl-"));
  process.env.SIRAYA_DATA_DIR = tmp;
  const manifest = initializeTemplates({ BUSINESS_NAME: "Test Cafe" });
  assert.ok(manifest.templates.length >= 5);
  const std = loadTemplateById("standard-receipt");
  assert.equal(std.version, 2);
  assert.equal(std.name, "Standard Receipt");
});

test("resolveTemplateForJob picks kitchen default", () => {
  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "siraya-tpl2-"));
  process.env.SIRAYA_DATA_DIR = tmp;
  initializeTemplates();
  const t = resolveTemplateForJob({ receiptKind: "kitchen_ticket" });
  assert.equal(t.receiptKind, "kitchen_ticket");
});

test("cloneTemplate creates copy", () => {
  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "siraya-tpl3-"));
  process.env.SIRAYA_DATA_DIR = tmp;
  initializeTemplates();
  const cloned = cloneTemplate("standard-receipt", "my-copy", "My Copy");
  assert.equal(cloned.id, "my-copy");
  assert.equal(cloned.name, "My Copy");
});

test("validateTemplate rejects invalid", () => {
  assert.throws(
    () => validateTemplate({ version: 1, id: "x", name: "y" }),
    /Unsupported template version/,
  );
});
