import { serverGet } from '@/lib/api'
import type { Paginated } from '@/lib/types'
import type { Post } from './posts'

interface ApiPost {
  id: number
  title: string
  slug: string
  excerpt?: string | null
  cover_image?: string | null
  author_name?: string | null
  published_at?: string | null
  date?: string | null
  body?: string | null
  meta_title?: string | null
  meta_description?: string | null
}

function mapPost(a: ApiPost): Post {
  return {
    slug: a.slug,
    title: a.title,
    excerpt: a.excerpt ?? '',
    date: a.date ?? a.published_at ?? '',
    cover_image: a.cover_image ?? null,
    author_name: a.author_name ?? null,
    body: a.body ?? null,
    meta_title: a.meta_title ?? null,
    meta_description: a.meta_description ?? null,
  }
}

export async function getPosts(): Promise<Post[]> {
  try {
    const r = await serverGet<Paginated<ApiPost>>('/posts', 300)
    return (r.data ?? []).map(mapPost)
  } catch {
    return []
  }
}

export async function getPost(slug: string): Promise<Post | null> {
  try {
    const r = await serverGet<{ data: ApiPost } | ApiPost>(`/posts/${slug}`, 300)
    const a = (r as { data?: ApiPost }).data ?? (r as ApiPost)
    if (a && a.slug) return mapPost(a)
  } catch {
    /* no static fallback — real data only */
  }
  return null
}

export async function getPostSlugs(): Promise<string[]> {
  try {
    const r = await serverGet<Paginated<ApiPost>>('/posts', 300)
    return (r.data ?? []).map((p) => p.slug)
  } catch {
    return []
  }
}
