import { getPublicSiteAbsoluteUrl } from "@/lib/mail-urls";
import { getPublishedMarketingBlogPostsPage } from "@/lib/marketing-blog";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

function escapeXml(value: string) {
  return value
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&apos;");
}

export async function GET() {
  const page = await getPublishedMarketingBlogPostsPage({ limit: 24 }).catch(() => ({
    hasMore: false,
    posts: [],
  }));
  const blogUrl = getPublicSiteAbsoluteUrl("/blog");
  const feedUrl = getPublicSiteAbsoluteUrl("/feed.xml");
  const items = page.posts.map((post) => {
    const url = getPublicSiteAbsoluteUrl(`/blog/${post.slug}`);
    const publishedAt = post.publishedAt ?? post.updatedAt;

    return [
      "<item>",
      `<title>${escapeXml(post.title)}</title>`,
      `<link>${escapeXml(url)}</link>`,
      `<guid isPermaLink="true">${escapeXml(url)}</guid>`,
      `<description>${escapeXml(post.excerpt)}</description>`,
      `<pubDate>${new Date(publishedAt).toUTCString()}</pubDate>`,
      "</item>",
    ].join("");
  }).join("");
  const lastBuildDate = page.posts[0]?.updatedAt
    ? new Date(page.posts[0].updatedAt).toUTCString()
    : new Date("2026-07-24T00:00:00+09:00").toUTCString();
  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>${escapeXml(blogUrl)}</link>`,
    `<atom:link href="${escapeXml(feedUrl)}" rel="self" type="application/rss+xml" />`,
    "<description>기업메일, 도메인 연결, SPF·DKIM, AI 메일 요약과 팀 메일 운영을 다루는 오피셜메일 공식 블로그</description>",
    "<language>ko-KR</language>",
    `<lastBuildDate>${lastBuildDate}</lastBuildDate>`,
    items,
    "</channel>",
    "</rss>",
  ].join("");

  return new Response(xml, {
    headers: {
      "Cache-Control": "public, s-maxage=900, stale-while-revalidate=86400",
      "Content-Language": "ko-KR",
      "Content-Type": "application/rss+xml; charset=utf-8",
      "Link": `<${feedUrl}>; rel="canonical"`,
    },
  });
}
