import rss from "@astrojs/rss";
import type { APIRoute } from "astro";
import { getCollection } from "astro:content";
import sanitizeHtml from "sanitize-html";
import MarkdownIt from "markdown-it";
const parser = new MarkdownIt();

export const GET: APIRoute = async (context) => {
  const blog = await getCollection("blog");

  const latestModDate = blog.reduce((latest, article) => {
    const modDate = article.data.modDate || article.data.pubDate;
    return modDate > latest ? modDate : latest;
  }, new Date(0));

  return rss({
    title: "Thilo Hohlt's blog",
    description:
      "Friendly technical articles with a focus on web and GNU/Linux topics.",
    site: context.url.origin,
    xmlns: {
      atom: "http://www.w3.org/2005/Atom",
    },
    customData: `
      <lastBuildDate>${latestModDate.toUTCString()}</lastBuildDate>
      <atom:link href="${context.url.origin}/rss.xml" rel="self" type="application/rss+xml" />
    `,
    items: blog.map(({ id, body, data }) => ({
      link: `/blog/${id}/`,
      content: sanitizeHtml(parser.render(body ?? ""), {
        allowedTags: sanitizeHtml.defaults.allowedTags.concat(["img"]),
      }),
      ...data,
    })),
  });
};
