/**
 * Shared API response helpers.
 *
 * Extracted from 10+ composables/components that each had an identical local
 * copy of extractCollection (parsing hydra:member / member / data / array).
 */

export function extractTotal(payload: unknown, fallbackLength: number): number {
  const p = payload as Record<string, unknown> | null
  if (typeof p?.totalItems === 'number') return p.totalItems
  if (typeof p?.['hydra:totalItems'] === 'number') return p['hydra:totalItems']
  return fallbackLength
}

export function extractCollection<T = any>(payload: unknown): T[] {
  if (Array.isArray(payload)) return payload as T[]
  const p = payload as Record<string, unknown> | null
  if (Array.isArray(p?.member)) return p!.member as T[]
  if (Array.isArray(p?.['hydra:member'])) return p!['hydra:member'] as T[]
  if (Array.isArray(p?.items)) return p!.items as T[]
  if (Array.isArray(p?.data)) return p!.data as T[]
  return []
}
