/**
 * Normalise list payloads from SAT backend controllers ({ success, data: T[] }) and legacy shapes.
 * @param {import('axios').AxiosResponse} res
 * @returns {unknown[]}
 */
export function listFromSatResponse(res) {
  const body = res?.data;
  if (body == null) return [];
  if (Array.isArray(body)) return body;
  if (Array.isArray(body.data)) return body.data;
  if (Array.isArray(body.rows)) return body.rows;
  return [];
}

/**
 * Label for a site row from SAT locations APIs (snake_case, legacy PascalCase, camelCase, or empty DB).
 */
export function getLocationDisplayName(loc) {
  if (loc == null || typeof loc !== 'object') return '';
  const raw =
    loc.location_name ??
    loc.Location_name ??
    loc.locationName ??
    loc.name ??
    loc.site_name;
  if (raw !== undefined && raw !== null && String(raw).trim() !== '') {
    return String(raw).trim();
  }
  const id = loc.location_id ?? loc.locationId ?? loc.id;
  if (id != null && id !== '') return `Site ${id}`;
  return 'Unknown site';
}

/** Numeric id for keys and comparisons with form state (location_ids). */
export function getLocationRowId(loc) {
  if (loc == null || typeof loc !== 'object') return NaN;
  const id = loc.location_id ?? loc.locationId ?? loc.id;
  if (id == null || id === '') return NaN;
  const n = Number(id);
  return Number.isFinite(n) ? n : NaN;
}
