import { NextResponse } from 'next/server';
export const dynamic = 'force-dynamic';
export async function GET() {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://canina.ir';
const apiUrl = process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4001/api';
const apiBase = apiUrl.endsWith('/api') ? apiUrl : `${apiUrl.replace(/\/$/, '')}/api`;
let blogs: any[] = [];
try {
const res = await fetch(`${apiBase}/blogs?page=1&limit=50`, { next: { revalidate: 3600 } });
if (res.ok) {
const data = await res.json();
blogs = (data.data || []).filter((b: any) => !b.noIndex && b.status === 'PUBLISHED');
}
} catch (e) {
console.error('Error fetching blogs for RSS feed:', e);
}
const itemsXml = blogs
.map((b) => {
const title = escapeXml(b.title || '');
const link = `${baseUrl}/blog/${b.slug}`;
const description = escapeXml(b.excerpt || b.metaDescription || '');
const pubDate = b.publishedAt ? new Date(b.publishedAt).toUTCString() : b.createdAt ? new Date(b.createdAt).toUTCString() : new Date().toUTCString();
const author = escapeXml(b.author ? `${b.author.firstName || ''} ${b.author.lastName || ''}`.trim() : 'کنینا فارما');
const category = escapeXml(b.category?.name || 'دانشنامه سلامت حیوانات');
return `
-
${title}
${link}
${link}
${pubDate}
${author}
${category}
${b.imageUrl ? `` : ''}
`;
})
.join('');
const rssFeed = `
مجله سلامت و دانشنامه تخصصی کنینا (Canina Pharma)
${baseUrl}/blog
جدیدترین مقالات علمی در زمینه مکملهای تخصصی، تغذیه و سلامت سگ و گربه از داروسازی کنینا آلمان
fa-ir
${new Date().toUTCString()}
${itemsXml}
`;
return new NextResponse(rssFeed, {
headers: {
'Content-Type': 'application/xml; charset=utf-8',
'Cache-Control': 'public, s-maxage=3600, stale-while-revalidate=86400',
},
});
}
function escapeXml(unsafe: string): string {
return unsafe.replace(/[<>&'"]/g, (c) => {
switch (c) {
case '<':
return '<';
case '>':
return '>';
case '&':
return '&';
case '\'':
return ''';
case '"':
return '"';
default:
return c;
}
});
}