import rss, { type RSSFeedItem } from '@astrojs/rss'
import type { APIRoute } from 'astro'
import {
  getBlog,
  listBlogs,
  type ListBlogItemType,
} from '../lib/apis/legacy/blog'
import { ensureShikiEngine } from '../lib/markdown'
// import { toMarkdocTree } from '../lib/markdoc'
import Markdoc from '@markdoc/markdoc'

export const prerender = false

export const GET = (async (context) => {
  let blogs: ListBlogItemType[] = []
  let pid = 0

  let newBlogs = []

  while (pid == 0 || newBlogs.length > 0) {
    newBlogs = await listBlogs({
      page: ++pid,
      limit: 100,
    })
    blogs = [...blogs, ...newBlogs]
  }

  const site = context.site || 'https://passthem.top'
  await ensureShikiEngine()

  return rss({
    title: '小帕的小窝',
    description: '小帕和他朋友们的博客',
    site,
    items: await Promise.all(
      blogs.map(async (blog) => {
        const blogContent =
          (await getBlog(blog.id))?.content || '博客内容暂不可用'
        // const blogTree = await toMarkdocTree(blogContent)
        const blogTree = Markdoc.transform(Markdoc.parse(blogContent))
        const html = Markdoc.renderers.html(blogTree)

        const rssItem: RSSFeedItem = {
          title: blog.title,
          description: `一篇由 ${blog.author.nickname} 写的博客`,
          link: `${site}/blogs/${blog.id}`,
          pubDate: new Date(blog.created_at),
          content: html,
          author: blog.author.nickname,
          enclosure: blog.featured_image
            ? {
                url: blog.featured_image.image_url,
                length: 0,
                type: 'image/jpeg',
              }
            : undefined,
        }

        return rssItem
      }),
    ),
    customData: `<language>zh-hans</language>`,
  })
}) satisfies APIRoute
