/**
 * DMS type mapping constants.
 * CAREFUL: the values here are used as canonical "mode" strings elsewhere in the app.
 * @type {{reynolds: string, cdk: string, pbs: string, fortellis: string}}
 */
export const DMS_MAP = {
  reynolds: "rr",
  cdk: "cdk",
  pbs: "pbs",
  fortellis: "fortellis"
};

/**
 * Determines the DMS type for a given bodyshop object.
 * @param bodyshop
 * @returns {*|string}
 */
export const determineDMSTypeByBodyshop = (bodyshop) => {
  const dmsMapping = {
    cdk_dealerid: DMS_MAP.cdk,
    pbs_serialnumber: DMS_MAP.pbs,
    rr_dealerid: DMS_MAP.reynolds
  };

  return Object.keys(dmsMapping).find((key) => bodyshop[key])
    ? dmsMapping[Object.keys(dmsMapping).find((key) => bodyshop[key])]
    : DMS_MAP.pbs;
};

/**
 * Determines the translation key for a given DMS type.
 * @param dmsType
 * @returns {*|string}
 */
export const determineDmsTypeTranslationKey = (dmsType) => {
  const dmsTypeMapping = {
    [DMS_MAP.cdk]: "bodyshop.labels.dms.cdk",
    [DMS_MAP.pbs]: "bodyshop.labels.dms.pbs",
    [DMS_MAP.reynolds]: "bodyshop.labels.dms.rr"
  };

  return dmsTypeMapping[dmsType] || dmsTypeMapping[DMS_MAP.pbs];
};

/**
 * Returns a normalized "mode" we can switch on:
 * @param bodyshop
 * @param fortellisTreatment
 * @returns {*|string|string}
 */
export const getDmsMode = (bodyshop, fortellisTreatment) => {
  const base = determineDMSTypeByBodyshop(bodyshop); // "rr" | "cdk" | "pbs" | undefined
  if (base === DMS_MAP.cdk && fortellisTreatment === "on") return DMS_MAP.fortellis;
  return base ?? "none";
};

/**
 * Checks if the DMS mode uses WSS.
 * @param mode
 * @returns {boolean}
 */
export const isWssMode = (mode) => {
  return mode === DMS_MAP.reynolds || mode === DMS_MAP.fortellis;
};

/**
 * Checks if the bodyshop has any DMS key configured.
 * @param bodyshop
 * @returns {*|string}
 */
export const bodyshopHasDmsKey = (bodyshop) =>
  bodyshop.cdk_dealerid || bodyshop.pbs_serialnumber || bodyshop.rr_dealerid;

/**
 * Resolve RR OpCode from bodyshop.rr_configuration.defaults
 * Is Duplicated on server/rr/rr-utils.js
 * @param bodyshop
 * @returns {`${string}${string}${string}`}
 */
export const resolveRROpCodeFromBodyshop = (bodyshop) => {
  if (!bodyshop) throw new Error("bodyshop is required");

  const cfg = bodyshop?.rr_configuration || {};
  const defaults = cfg?.defaults || {};

  const prefix = (defaults.prefix ?? "").toString().trim();
  const base = (defaults.base ?? "").toString().trim();
  const suffix = (defaults.suffix ?? "").toString().trim();

  if (!prefix && !base && !suffix) {
    throw new Error("No RR OpCode parts found in bodyshop configuration");
  }

  return `${prefix}${base}${suffix}`;
};
