export function toList(payload) {
  if (Array.isArray(payload)) return payload;
  if (Array.isArray(payload?.items)) return payload.items;
  if (Array.isArray(payload?.results)) return payload.results;
  if (Array.isArray(payload?.content)) return payload.content;
  if (Array.isArray(payload?.data)) return payload.data;
  return [];
}

export function toEntity(payload) {
  return payload?.item ?? payload?.content ?? payload?.data ?? payload;
}

export function normalizeContentItem(item) {
  if (!item) return item;

  return {
    ...item,
    slug: item.slug ?? item.id,
    excerpt: item.excerpt ?? item.summary ?? item.description ?? "",
    image: item.image ?? item.coverUrl ?? item.cover ?? item.media?.[0]?.url,
    publishedAt: item.publishedAt ?? item.createdAt ?? item.date ?? "",
    readingTime: item.readingTime ?? item.readingMinutes ?? 1,
    views: item.views ?? item.viewCount ?? 0,
    tags: item.tags ?? [],
    category: item.category?.name ?? item.category ?? "",
    author: item.author?.name ?? item.author ?? item.user?.name ?? "",
  };
}

export function normalizeContentList(payload) {
  return toList(payload).map(normalizeContentItem);
}
