import { Feed } from 'feed'
import { mkdir, writeFile } from 'fs/promises'

import { RenderBlockList } from '@/lib/notion/utils/renderNotionContent'

import { getAllBlogPosts } from './notion/content/blogPosts'
import getBlockRecursively from './notion/utils/getBlockRecursively'
import richTextAsPlainText from './notion/utils/richTextToPlainText'

export async function generateRssFeed() {
  const blogPosts = await getAllBlogPosts()
  const siteUrl = process.env.NEXT_PUBLIC_SITE_URL!

  const author = {
    name: 'Filipe Medeiros',
    email: 'hello@filipesm.eu',
    link: 'filipesm.eu',
  }

  const feed = new Feed({
    title: author.name,
    description:
      'Blog pessoal do Filipe Medeiros. Escreve sobre tópicos diversos, maioritariamente de tecnologia, política, economia e atualidade.',
    author,
    id: siteUrl,
    link: siteUrl,
    image: `${siteUrl}/favicon.ico`,
    favicon: `${siteUrl}/favicon.ico`,
    copyright: `Todos os direitos reservados ${new Date().getFullYear()}`,
    feedLinks: {
      rss2: `${siteUrl}/rss/feed.xml`,
      json: `${siteUrl}/rss/feed.json`,
    },
  })

  await Promise.all(
    blogPosts.map(async (blogPost) => {
      const url = `${siteUrl}/blog/${richTextAsPlainText(
        blogPost.properties.Slug.rich_text,
      )}`
      const content = await getBlockRecursively(blogPost.id)
      const html = (await import('react-dom/server')).renderToStaticMarkup(
        // @ts-expect-error I don't know why but React's types seem wrong
        () => <RenderBlockList blockList={content} />,
      )

      feed.addItem({
        title: richTextAsPlainText(blogPost.properties.Name.title),
        id: url,
        link: url,
        description: richTextAsPlainText(
          blogPost.properties.Description.rich_text,
        ),
        content: html,
        author: [author],
        contributor: [author],
        date: new Date(
          blogPost.properties.PublishDate.date?.start ?? blogPost.created_time,
        ),
      })
    }),
  )

  await mkdir('./public/rss', { recursive: true })
  await Promise.all([
    writeFile('./public/rss/feed.xml', feed.rss2(), 'utf8'),
    writeFile('./public/rss/feed.json', feed.json1(), 'utf8'),
  ])
}
