type JsonRecord = Record<string, unknown>;

function isRecord(value: unknown): value is JsonRecord {
  return typeof value === 'object' && value !== null && !Array.isArray(value);
}

/**
 * Accepts the response shapes used across the legacy Velocity API, the newer
 * WebOS API, and paginated read endpoints. Components should render arrays,
 * not transport envelopes.
 */
export function unwrapArray<T>(payload: unknown, keys: string[] = []): T[] {
  if (Array.isArray(payload)) return payload as T[];
  if (!isRecord(payload)) return [];

  for (const key of [...keys, 'data', 'items', 'results', 'records', 'rows', 'value']) {
    const candidate = payload[key];
    if (Array.isArray(candidate)) return candidate as T[];
  }

  return [];
}

export function unwrapObject<T>(payload: unknown, keys: string[] = []): T | undefined {
  if (!isRecord(payload)) return undefined;

  for (const key of [...keys, 'data', 'record', 'result', 'item', 'value']) {
    const candidate = payload[key];
    if (isRecord(candidate)) return candidate as T;
  }

  return payload as T;
}

export function stableArray<T>(value: unknown): T[] {
  return Array.isArray(value) ? value as T[] : [];
}
