
import type { Post } from '../interfaces'

export async function getPostByPageId(pageId: string): Promise<Post | null> {
  if (!pageId) return null

  try {
    const res = await fetch("https://notion-api.nvme0n1p.dev/v2/posts")
    if (!res.ok) throw new Error(`Failed to fetch posts: ${res.status}`)

    const payload = (await res.json()) as { posts?: any[] }
    const match = (payload.posts ?? []).find((post) => post.id === pageId)
    if (!match) return null

    const dateString =
      match['Published Date'] || match.created_time || new Date().toISOString()

    return {
      PageId: match.id,
      Title: match.Content || match.slug || 'Untitled',
      Icon: null,
      Cover: null,
      Slug: match.slug || match.id,
      Date: dateString,
      Tags: Array.isArray(match.Tags)
        ? match.Tags.map((name: string) => ({
            id: name,
            name,
            color: 'default',
          }))
        : [],
      Excerpt: match.excerpt || '',
      FeaturedImage: null,
      Rank: Number(match.rank || 0),
    }
  } catch (error) {
    console.error('getPostByPageId error:', error)
    return null
  }
}
