import rss from "@astrojs/rss";
import type { APIContext } from "astro";
import { getPosts } from "../../lib/cms";
import { sortPostsByDate, filterHiddenPosts, postHref } from "../../lib/blog-utils";

export const prerender = true;

export async function GET(context: APIContext) {
  const site = context.site ?? new URL("https://windwiderstand.de");
  let posts: Awaited<ReturnType<typeof getPosts>> = [];
  try {
    posts = filterHiddenPosts(sortPostsByDate(await getPosts()));
  } catch {
    posts = [];
  }

  return rss({
    title: "Bürgerinitiative Vachdorf – Beiträge",
    description: "Aktuelles zur Windkraft, Gesundheit und Region.",
    site,
    items: posts.map((p) => {
      const createdRaw = (p as { _created?: string; created?: string }).created ?? (p as { _created?: string })._created;
      const pubDate = createdRaw ? new Date(createdRaw) : undefined;
      return {
        title: p.headline ?? p.slug ?? "",
        description: p.excerpt ?? p.subheadline ?? "",
        link: postHref(p),
        pubDate: pubDate && !Number.isNaN(pubDate.getTime()) ? pubDate : undefined,
      };
    }),
    customData: `<language>de-de</language>`,
  });
}
