import { prisma } from "@/lib/db";

const SITE_URL = "https://biztaghavi.com";

export async function GET() {
  const posts = await prisma.post.findMany({
    where: { locale: "fa", publishedAt: { lte: new Date() } },
    orderBy: { publishedAt: "desc" },
    take: 20,
    select: { id: true, title: true, slug: true, excerpt: true, publishedAt: true, category: true },
  });

  const items = posts
    .map((post) => {
      const url = `${SITE_URL}/writing/${post.slug}`;
      const date = post.publishedAt ? new Date(post.publishedAt).toUTCString() : "";
      return `
    <item>
      <title><![CDATA[${post.title}]]></title>
      <link>${url}</link>
      <guid>${url}</guid>
      <pubDate>${date}</pubDate>
      <category>${post.category}</category>
      ${post.excerpt ? `<description><![CDATA[${post.excerpt}]]></description>` : ""}
    </item>`;
    })
    .join("\n");

  const xml = `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>علی تقوی — نوشته‌ها</title>
    <link>${SITE_URL}</link>
    <description>یادداشت‌ها، تحلیل‌ها و آموخته‌هایم از ساختن کسب‌وکار، محصول و برند</description>
    <language>fa</language>
    <atom:link href="${SITE_URL}/api/rss" rel="self" type="application/rss+xml" />
    ${items}
  </channel>
</rss>`;

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