import RSS from "rss";
import { getCachedPosts } from "@/services/wp";

export async function GET() {
  const site_url = process.env.SITE_URL || "http://localhost:8000";
  const feed = new RSS({
    title: "Teapot Insights",
    description: "A deep dive into tech, trends and teachable moments.",
    feed_url: `${site_url}/feed.xml`,
    site_url: `${site_url}/`,
    language: "en-GB",
    pubDate: new Date().toUTCString(),
    ttl: 60,
  });

  const posts = await getCachedPosts(1, 99);

  if (posts.posts.length > 0) {
    posts.posts.map((post: any) => {
      feed.item({
        title: post.title.rendered,
        description: post.excerpt.rendered,
        url: `${site_url}/insights/${post.slug}`,
        author: post.author_name,
        date: post.date,
      });
    });
  }

  return new Response(feed.xml({ indent: true }), {
    status: 200,
    headers: {
      "Content-Type": "application/xml; charset=utf-8",
    },
  });
}
