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

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

  try {
    const payload = await fetchNotionApiJson<{ posts?: any[] }>('/v2/posts')
    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
  }
}
