import GhostContentAPI, { type PostsOrPages } from '@tryghost/content-api'

export interface NewsPostAuthor {
  id: string | undefined,
  name: string | undefined,
  slug: string | undefined,
  profileImage: string | undefined,
  url: string | undefined
}

export interface NewsPost {
  id: string,
  uuid: string | undefined,
  title: string | undefined,
  featureImage: string | undefined,
  featureImageAlt: string | undefined,
  createdAt: string | undefined,
  updatedAt: string | undefined,
  publishedAt: string | undefined,
  slug: string,
  url: string | undefined,
  excerpt: string | undefined,
  customExcerpt: string | undefined,
  readingTime: number | undefined,
  primaryAuthor: NewsPostAuthor | undefined
}

export async function getPosts() {
  const newsApi = new GhostContentAPI({
    url: 'https://sbanews.manticorum.com',
    key: '37abf30917ce55d6d9155b537d',
    version: "v5.0"
  })

  const posts: PostsOrPages = await newsApi.posts.browse({
    limit: 4,
    include: ['authors', 'tags'],
  })

  return makeNewPostsFromPostsOrPages(posts)
}

function makeNewPostsFromPostsOrPages(posts: PostsOrPages): NewsPost[] {
  return posts.map(p => {
    return {
      id: p.id,
      uuid: p.uuid,
      title: p.title,
      featureImage: p.feature_image ?? undefined,
      featureImageAlt: p.feature_image_alt ?? undefined,
      createdAt: p.created_at ?? undefined,
      updatedAt: p.updated_at ?? undefined,
      publishedAt: p.published_at ?? undefined,
      slug: p.slug,
      url: p.url,
      excerpt: p.excerpt,
      customExcerpt: p.custom_excerpt,
      readingTime: p.reading_time,
      primaryAuthor: {
        id: p.primary_author?.id,
        name: p.primary_author?.name,
        slug: p.primary_author?.slug,
        profileImage: p.primary_author?.profile_image ?? undefined,
        url: p.primary_author?.url ?? undefined
      }
    }
  })
}

