const fs = require("fs");
const path = require("path");
const { getSirayaDataRoot } = require("./paths");

function getTemplatePath() {
  return path.join(getSirayaDataRoot(), "receipt-template.json");
}

function getDefaultTemplate(businessConfig = {}) {
  const cfg = businessConfig || {};
  return {
    version: 1,
    paperWidth: 32,
    header: {
      showLogo: false,
      title: "",
      lines: [],
      align: "center",
    },
    sections: {
      orderMeta: true,
      items: true,
      totals: true,
      loyalty: true,
      payment: true,
      footer: true,
    },
    footer: {
      lines: ["Thank you for your order!", "Please visit again!"],
      align: "center",
    },
    styles: {
      titleSize: "large",
      currencyPrefix: "Rs ",
    },
  };
}

function validateTemplate(t) {
  if (!t || typeof t !== "object") {
    throw new Error("Template must be an object");
  }
  if (t.version !== 1) {
    throw new Error("Unsupported template version");
  }
  if (!t.header || typeof t.header !== "object") {
    throw new Error("Template header required");
  }
  if (!t.sections || typeof t.sections !== "object") {
    throw new Error("Template sections required");
  }
  return t;
}

function loadTemplate(businessConfig) {
  const filePath = getTemplatePath();
  if (!fs.existsSync(filePath)) {
    return getDefaultTemplate(businessConfig);
  }
  try {
    const raw = JSON.parse(fs.readFileSync(filePath, "utf8"));
    return validateTemplate(raw);
  } catch {
    return getDefaultTemplate(businessConfig);
  }
}

function saveTemplate(template) {
  const validated = validateTemplate(template);
  const filePath = getTemplatePath();
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
  fs.writeFileSync(filePath, JSON.stringify(validated, null, 2), "utf8");
  return validated;
}

module.exports = {
  getTemplatePath,
  getDefaultTemplate,
  loadTemplate,
  saveTemplate,
  validateTemplate,
};
