// src/app/sitemap.xml/route.js

// Import your blog posts helper (adjust path if needed)
import { getAllBlogPosts } from '@/lib/blog';

function generateSiteMap(posts) {
  const staticPages = [
    { url: '', priority: 1.0, changefreq: 'weekly' },
    { url: '/services', priority: 0.9, changefreq: 'weekly' },
    { url: '/about', priority: 0.8, changefreq: 'monthly' },
    { url: '/contact', priority: 0.8, changefreq: 'monthly' },
    { url: '/pricing', priority: 0.8, changefreq: 'monthly' },
    { url: '/blog', priority: 0.7, changefreq: 'daily' },
    { url: '/pci-dss-compliance', priority: 0.9, changefreq: 'monthly' }, // important page
  ];

  const now = new Date().toISOString();

  const staticXml = staticPages
    .map(({ url, priority, changefreq }) => {
      return `
  <url>
    <loc>https://arclogiq.com${url}</loc>
    <lastmod>${now}</lastmod>
    <changefreq>${changefreq}</changefreq>
    <priority>${priority}</priority>
  </url>`;
    })
    .join('');

  const postsXml = posts
    .map(({ slug, date }) => {
      const lastmod = date || now;
      return `
  <url>
    <loc>https://arclogiq.com/blog/${slug}</loc>
    <lastmod>${lastmod}</lastmod>
    <changefreq>monthly</changefreq>
    <priority>0.6</priority>
  </url>`;
    })
    .join('');

  return `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${staticXml}
${postsXml}
</urlset>`;
}

export async function GET() {
  let posts = [];

  try {
    posts = await getAllBlogPosts();
  } catch (e) {
    // Fallback so sitemap still works even if blog throws
    posts = [];
  }

  const body = generateSiteMap(posts);

  return new Response(body, {
    status: 200,
    headers: {
      'Content-Type': 'text/xml',
    },
  });
}
