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