import { Feed } from 'feed';
import { getFilteredBlogPosts } from '~~/lib/blog/read-posts';

const BASE_URL = 'https://lunasqu.ee/blog';

export default defineEventHandler(async (event) => {
  const posts = await getFilteredBlogPosts(undefined, true, false);
  const feed = new Feed({
    title: "Evert's Blog",
    description: 'Projects and Tutorials',
    id: BASE_URL,
    link: BASE_URL,
    copyright: 'Evert "Diamond" Prants 2024',
    language: 'en',
    updated: new Date(posts[0].date),
    generator: 'https://git.icynet.eu/evert/lunasqu.ee-nuxt',
    feedLinks: {
      atom: `${BASE_URL}/atom.xml`,
    },
  });

  posts.forEach((post) => {
    const description = post.summary
      .replace(/<[^>]*>?/gm, '')
      .replace('\n', ' ')
      .substring(0, 240);

    feed.addItem({
      title: post.title,
      id: `${BASE_URL}/${post.fullSlug}`,
      link: `${BASE_URL}/${post.fullSlug}`,
      description,
      content: post.html,
      date: new Date(post.date),
      published: new Date(post.date),
      category: post.tags.map((tag) => ({
        term: tag,
        scheme: `${BASE_URL}/tags/${tag}`,
      })),
    });
  });

  appendResponseHeader(event, 'Content-Type', 'text/xml');

  return feed.atom1();
});
