import { NextResponse } from "next/server";
import { connectDB } from "@/lib/db";
import { BlogPost } from "@/models/BlogPost";
import { getSiteUrl } from "@/lib/seo";

export const dynamic = "force-dynamic";

function escapeXml(s: string): string {
  return s.replace(/[<>&'"]/g, (c) => ({ "<": "&lt;", ">": "&gt;", "&": "&amp;", "'": "&apos;", '"': "&quot;" })[c] as string);
}

// Deutschsprachiger Feed (Standardsprache der Seite) — bewusst kein
// separater EN-Feed, um die Pflege nicht unnötig zu verdoppeln.
export async function GET() {
  await connectDB();
  // Keine geplanten (publishedAt in der Zukunft) Beiträge in den Feed.
  const posts = await BlogPost.find({ visible: true, publishedAt: { $not: { $gt: new Date() } } })
    .sort({ publishedAt: -1 })
    .limit(30)
    .lean();
  const siteUrl = getSiteUrl();

  const items = posts
    .map((p) => {
      const link = `${siteUrl}/de/blog/${p.slug}`;
      const description = p.excerpt || p.content.slice(0, 300);
      return `  <item>
    <title>${escapeXml(p.title)}</title>
    <link>${link}</link>
    <guid>${link}</guid>
    <pubDate>${new Date(p.publishedAt).toUTCString()}</pubDate>
    <description>${escapeXml(description)}</description>
  </item>`;
    })
    .join("\n");

  const xml = `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
  <title>Rakku Photography — Blog</title>
  <link>${siteUrl}/de/blog</link>
  <description>Behind the Scenes von aktuellen Shootings und Conventions mit Rakku Photography.</description>
  <language>de-DE</language>
${items}
</channel>
</rss>`;

  return new NextResponse(xml, {
    headers: {
      "Content-Type": "application/rss+xml; charset=utf-8",
      "Cache-Control": "public, max-age=3600",
    },
  });
}
