import type { APIRoute } from 'astro';
import { getCollection } from 'astro:content';

const site = 'https://workroot.in';

interface SitemapEntry {
  url: string;
  lastmod?: string;
  changefreq: 'always' | 'hourly' | 'daily' | 'weekly' | 'monthly' | 'yearly' | 'never';
  priority: number;
}

export const GET: APIRoute = async () => {
  // Fetch blog posts (exclude drafts)
  const posts = await getCollection('blog', ({ data }) => !data.draft);

  // Fetch portfolio items if collection exists
  let portfolioItems: any[] = [];
  try {
    portfolioItems = await getCollection('portfolio');
  } catch (e) {
    // Portfolio collection doesn't exist yet
  }

  const staticPages: SitemapEntry[] = [
    { url: '/', changefreq: 'weekly', priority: 1.0 },
    { url: '/services/', changefreq: 'monthly', priority: 0.9 },
    // Keyword-focused service landing pages
    { url: '/services/custom-erp-development/', changefreq: 'monthly', priority: 0.8 },
    { url: '/services/government-it-solutions-gem-vendor/', changefreq: 'monthly', priority: 0.8 },
    { url: '/services/police-management-system/', changefreq: 'monthly', priority: 0.8 },
    { url: '/services/react-native-app-development/', changefreq: 'monthly', priority: 0.8 },
    { url: '/services/university-erp/', changefreq: 'monthly', priority: 0.8 },
    { url: '/portfolio/', changefreq: 'weekly', priority: 0.8 },
    { url: '/about/', changefreq: 'monthly', priority: 0.8 },
    { url: '/blog/', changefreq: 'weekly', priority: 0.8 },
    { url: '/contact/', changefreq: 'monthly', priority: 0.7 },
    { url: '/privacy/', changefreq: 'yearly', priority: 0.3 },
    { url: '/terms/', changefreq: 'yearly', priority: 0.3 },
    { url: '/sitemap/', changefreq: 'monthly', priority: 0.3 },
  ];

  const blogPages: SitemapEntry[] = posts.map((post) => ({
    url: `/blog/${post.slug}/`,
    lastmod: post.data.updatedDate
      ? post.data.updatedDate.toISOString().split('T')[0]
      : post.data.pubDate.toISOString().split('T')[0],
    changefreq: 'monthly' as const,
    priority: 0.7,
  }));

  const portfolioPages: SitemapEntry[] = portfolioItems.map((item) => ({
    url: `/portfolio/${item.slug}/`,
    lastmod: item.data.updatedDate
      ? item.data.updatedDate.toISOString().split('T')[0]
      : item.data.date?.toISOString().split('T')[0],
    changefreq: 'monthly' as const,
    priority: 0.7,
  }));

  const allPages = [...staticPages, ...blogPages, ...portfolioPages];

  const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:news="http://www.google.com/schemas/sitemap-news/0.9"
        xmlns:xhtml="http://www.w3.org/1999/xhtml"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
        xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">
${allPages
  .map(
    (page) => `  <url>
    <loc>${site}${page.url}</loc>${page.lastmod ? `
    <lastmod>${page.lastmod}</lastmod>` : `
    <lastmod>${new Date().toISOString().split('T')[0]}</lastmod>`}
    <changefreq>${page.changefreq}</changefreq>
    <priority>${page.priority}</priority>
  </url>`
  )
  .join('\n')}
</urlset>`;

  return new Response(sitemap, {
    headers: {
      'Content-Type': 'application/xml; charset=utf-8',
      'Cache-Control': 'public, max-age=3600', // Cache for 1 hour
      'X-Robots-Tag': 'noindex', // Don't index the sitemap itself
    },
  });
};
