/**
 * Ensure a value is a non-empty string, else throw
 * @param v
 * @param name
 * @returns {string}
 */
const requireString = (v, name) => {
  const s = (v ?? "").toString().trim();
  if (!s || s.toLowerCase() === "undefined" || s.toLowerCase() === "null") {
    throw new Error(`RR config missing: ${name}`);
  }
  return s;
};

/**
 * Get RR config from bodyshop record, with env fallbacks
 * @param bodyshop
 * @returns {{baseUrl: string, username: string, password: string, routing: {dealerNumber: string, storeNumber: string, areaNumber: string}, timeoutMs: number, retries: {max: number}}}
 */
const getRRConfigFromBodyshop = (bodyshop) => {
  const baseUrl = process.env.RR_BASE_URL;
  const username = process.env.RR_USERNAME;
  const password = process.env.RR_PASSWORD;

  const dealerNumber = bodyshop?.rr_dealerid ?? process.env.RR_DEALER_NUMBER;

  const bsCfg = bodyshop?.rr_configuration || {};

  const storeNumber = bsCfg?.storeNumber;
  const areaNumber = bsCfg?.branchNumber ?? bsCfg?.areaNumber;

  return {
    baseUrl: requireString(baseUrl, "baseUrl"),
    username: requireString(username, "username"),
    password: requireString(password, "password"),
    routing: {
      dealerNumber: requireString(String(dealerNumber), "routing.dealerNumber"),
      storeNumber: requireString(String(storeNumber), "routing.storeNumber"),
      areaNumber: requireString(String(areaNumber), "routing.areaNumber")
    },
    // timeouts / retries can be adjusted here
    timeoutMs: Number(process.env.RR_TIMEOUT_MS || 30000),
    retries: { max: Number(process.env.RR_RETRIES_MAX || 2) }
  };
};

module.exports = { getRRConfigFromBodyshop };
