/**
 * SAT API often returns { success, data: [...] }; some proxies may omit `success` or return the array at the top level.
 */
export function parseSatDataArray(res) {
  const d = res?.data;
  if (!d) return [];
  if (Array.isArray(d.data)) return d.data;
  if (Array.isArray(d)) return d;
  return [];
}

export function siteRowId(s) {
  if (s == null || typeof s !== "object") return "";
  const id =
    s.location_id ??
    s.Location_ID ??
    s.locationId ??
    s.LocationId ??
    s.id;
  if (id != null && id !== "") return id;
  for (const [k, v] of Object.entries(s)) {
    const lk = k.toLowerCase().replace(/_/g, "");
    if (lk === "locationid" && v != null && v !== "") return v;
  }
  return "";
}

export function siteRowLabel(s) {
  const id = siteRowId(s);
  const candidates = [
    s?.location_name,
    s?.Location_Name,
    s?.locationName,
    s?.LocationName,
    s?.site_name,
    s?.Site_Name,
    s?.siteName,
    s?.name,
  ];
  for (const v of candidates) {
    if (v != null && String(v).trim() !== "") return String(v);
  }
  if (s && typeof s === "object") {
    for (const [k, v] of Object.entries(s)) {
      if (v == null || typeof v === "object") continue;
      const str = String(v).trim();
      if (!str) continue;
      const lk = k.toLowerCase();
      if (
        (lk.includes("location") && lk.includes("name")) ||
        (lk.includes("site") && lk.includes("name")) ||
        lk === "name"
      ) {
        return str;
      }
    }
  }
  if (id !== "" && id != null) return `Site ${id}`;
  return "";
}

export function departmentRowId(w) {
  if (w == null || typeof w !== "object") return "";
  const id = w.department_id ?? w.Department_ID ?? w.departmentId ?? w.DepartmentId ?? w.id;
  if (id != null && id !== "") return id;
  for (const [k, v] of Object.entries(w)) {
    const lk = k.toLowerCase().replace(/_/g, "");
    if (lk === "departmentid" && v != null && v !== "") return v;
  }
  return "";
}

export function departmentRowLabel(w) {
  const id = departmentRowId(w);
  const candidates = [
    w?.department_name,
    w?.Department_Name,
    w?.departmentName,
    w?.DepartmentName,
    w?.name,
  ];
  for (const v of candidates) {
    if (v != null && String(v).trim() !== "") return String(v);
  }
  if (w && typeof w === "object") {
    for (const [k, v] of Object.entries(w)) {
      if (v == null || typeof v === "object") continue;
      const str = String(v).trim();
      if (!str) continue;
      const lk = k.toLowerCase();
      if ((lk.includes("department") && lk.includes("name")) || lk === "name") {
        return str;
      }
    }
  }
  if (id !== "" && id != null) return `Work area ${id}`;
  return "";
}
