import { a as w, t as H, f as T } from "./number-BVg7EKPV.js";
import { u as P } from "./feature-Cz6F0_cm.js";
import { useCoreStore as g } from "@feedmepos/mf-common";
import { a as y, g as k, l as j, d as S } from "./app-Bpb4394e.js";
import { b as N, d as $, s as I } from "./xlsx.util-BPV2vsSD.js";
import { f as _ } from "./date2-DpnYOzUg.js";
import { I as O } from "./rules-CoimOM7X.js";
function R() {
  return {
    low: 6,
    mid: 14
  };
}
const B = {
  _id: "",
  name: "",
  abbrev: "",
  precision: 0,
  measurements: []
};
function D(e) {
  return !e || Object.keys(e).length === 0 ? "" : Object.entries(e).map(([t, a]) => `${t}: ${a}`).join(", ");
}
function A(e) {
  if (!e || e.trim() === "")
    return;
  const t = {}, a = e.split(",").map((n) => n.trim());
  for (const n of a) {
    const s = n.indexOf(":");
    if (s > 0) {
      const c = n.substring(0, s).trim(), r = n.substring(s + 1).trim();
      c && r && (t[c] = r);
    }
  }
  return Object.keys(t).length > 0 ? t : void 0;
}
function V(e) {
  var a, n, s, c, r;
  return {
    code: e.code,
    name: e.name,
    unit: e.unit.name,
    baseUnit: e.unit.abbrev,
    measurementName: ((a = e.unit.measurements.find((m) => m.id === e.trackingMeasurement)) == null ? void 0 : a.abbrev) ?? e.unit.abbrev,
    valuationMethod: e.valuation ?? "WAVG",
    pricePerUnit: (n = e.defaultCost) != null && n.costPerUnit ? +w((s = e.defaultCost) == null ? void 0 : s.costPerUnit) : 0,
    thresholdLow: ((c = e.thresholds) == null ? void 0 : c.low) ?? R().low,
    thresholdMid: ((r = e.thresholds) == null ? void 0 : r.mid) ?? R().mid,
    customAttributes: D(e.customAttributes)
  };
}
function E() {
  var s;
  const e = [
    {
      id: "code",
      name: "Code"
    },
    {
      id: "name",
      name: "Name"
    },
    {
      id: "unit",
      name: "Unit"
    },
    {
      id: "baseUnit",
      name: "Base unit"
    },
    {
      id: "measurementName",
      name: "Measurement Name"
    }
  ], t = P(), a = g(), n = k(a.currentCountry.value);
  return t.enableTotalCost && e.push(
    {
      id: "valuationMethod",
      name: "Valuation method"
    },
    {
      id: "pricePerUnit",
      name: `Price per unit (${n == null ? void 0 : n.currency})`
    }
  ), ((s = a.currentBusiness.value) == null ? void 0 : s.menuVersion) === "v4" && e.push(
    {
      id: "thresholdLow",
      name: "Show RED when remaining"
    },
    {
      id: "thresholdMid",
      name: "Show YELLOW when remaining"
    }
  ), e.push({
    id: "customAttributes",
    name: "Custom Attributes"
  }), e;
}
function X() {
  const t = y().skus.map(V), n = g().currentBusiness.value, s = E(), c = [
    ["Business name:", n == null ? void 0 : n.name],
    ["Business ID:", n == null ? void 0 : n._id],
    ["Menu version", n == null ? void 0 : n.menuVersion],
    [],
    s.map((o) => o.name),
    ...t.map((o) => s.map((u) => o[u.id]))
  ], r = s.map((o) => `system:${o.id}`), m = N(c, r), d = `${n == null ? void 0 : n.name} ingredients (${_(/* @__PURE__ */ new Date())}).xlsx`;
  return $(m, d), d;
}
function Z() {
  const t = g().currentBusiness.value, a = E(), n = [
    ["Business name:", t == null ? void 0 : t.name],
    ["Business ID:", t == null ? void 0 : t._id],
    ["Menu version", t == null ? void 0 : t.menuVersion],
    [],
    a.map((m) => m.name)
  ], s = a.map((m) => `system:${m.id}`), c = N(n, s), r = "FeedMe ingredients template.xlsx";
  return $(c, r), r;
}
function L(e) {
  const [
    t,
    a,
    n,
    s,
    c,
    r,
    ...m
  ] = I(e);
  if (!t || !t.length || t.some((l) => l.length && !l.startsWith("system:")))
    throw new Error("Missing meta header. Excel file does not come from the template.");
  const d = t.map((l) => l.split(":")[1]), u = ["code", "name", "unit", "baseUnit", "measurementName"].filter((l) => !d.includes(l));
  if (u.length)
    throw new Error(
      `Missing meta headers (${u.join()}). Excel file does not come from the template.`
    );
  return m.map((l, h) => {
    const f = {};
    for (const v in d) {
      const b = d[v];
      Object.assign(f, { [b]: l[v] });
    }
    return {
      index: h,
      data: f
    };
  });
}
function U(e, t, a, { ignoreErrors: n = !1 } = {}) {
  var M;
  const c = y().units, r = new Array(), m = a.filter((i) => i.data.code === e.code);
  m.length > 1 && r.push(
    `Code ${e.code} is already used in row ${m.map((i) => i.index + 6).join()}.`
  );
  const d = c.find((i) => {
    var x, C;
    return i.abbrev === e.baseUnit && ((x = i.name) == null ? void 0 : x.trim()) === ((C = e.unit) == null ? void 0 : C.trim());
  }), o = d == null ? void 0 : d.measurements.find((i) => i.abbrev === e.measurementName);
  if (!d)
    r.push(`Cannot find base unit of symbol ${e.baseUnit}.`);
  else if (e.baseUnit !== e.measurementName && !o) {
    const i = `Cannot find unit conversion for ${e.baseUnit} with symbol ${e.measurementName || "[empty]"}.`;
    r.push(i);
  }
  const u = S.options.find(
    (i) => i === e.valuationMethod
  );
  e.valuationMethod && !u && r.push(
    `Expected valuation method to be one of ${S.options.join()} but got ${e.valuationMethod} instead.`
  );
  const l = g().currentCountry.value, h = (i) => `${i}`.length && O()(i) === !0, f = h(`${e.pricePerUnit}`) === !0 ? {
    costPerUnit: {
      ...H(Number(e.pricePerUnit) || 0, T(Number(e.pricePerUnit) || 0)),
      currency: ((M = k(l)) == null ? void 0 : M.currency) ?? "MYR"
    },
    measurement: o
  } : void 0, v = h(`${e.thresholdLow}`) && h(`${e.thresholdMid}`) ? {
    low: Number(e.thresholdLow) || 0,
    mid: Number(e.thresholdMid) || 0
  } : void 0, b = "customAttributes" in e ? A(e.customAttributes) : null;
  return {
    type: "create",
    sku: {
      code: e.code,
      name: e.name,
      unit: d ?? c.find((i) => i) ?? B,
      trackingMeasurement: o == null ? void 0 : o.id,
      valuation: u,
      defaultCost: f,
      thresholds: v,
      ...b !== null && { customAttributes: b }
    },
    errors: r,
    excelRowNumber: t + 6
  };
}
function ee(e) {
  try {
    const t = L(e).filter((o) => o.data.code), n = y().skus, s = j(n, "code"), c = t.filter((o) => !s[o.data.code]), r = t.filter((o) => s[o.data.code]), m = c.map(
      (o) => U(o.data, o.index, t)
    ), d = r.map((o) => {
      const u = U(o.data, o.index, t), p = s[o.data.code];
      let l = p.customAttributes;
      return "customAttributes" in o.data && (l = A(o.data.customAttributes)), {
        ...u,
        type: "update",
        original: p,
        sku: {
          // to maintain original props not in the import excel, e.g. inventory binding, etc...
          ...p,
          code: u.sku.code || p.code,
          name: u.sku.name || p.name,
          unit: u.sku.unit || p.unit,
          trackingMeasurement: u.sku.trackingMeasurement || p.trackingMeasurement,
          valuation: u.sku.valuation || p.valuation,
          defaultCost: u.sku.defaultCost || p.defaultCost,
          thresholds: u.sku.thresholds || p.thresholds,
          customAttributes: l
        }
      };
    });
    return {
      invalidExcel: !1,
      importCreateResult: m,
      importUpdateResult: d
    };
  } catch (t) {
    return {
      invalidExcel: !0,
      invalidExcelMessage: (t == null ? void 0 : t.message) ?? "Invalid excel",
      importCreateResult: [],
      importUpdateResult: []
    };
  }
}
export {
  Z as a,
  E as b,
  R as d,
  X as e,
  ee as g,
  A as s
};
