import { getPublishedPosts, getTagSummaries, getTotalPages } from '../lib/posts';
import { absoluteUrl, postUpdatedAt, xmlEscape } from '../lib/seo';
import { site } from '../lib/siteConfig';

type SitemapEntry = {
  path: string;
  lastmod?: string;
  changefreq?: 'daily' | 'weekly' | 'monthly' | 'yearly';
  priority?: string;
};

function formatLastmod(value?: string): string | undefined {
  if (!value) {
    return undefined;
  }

  const date = new Date(value);
  if (Number.isNaN(date.getTime())) {
    return undefined;
  }

  return date.toISOString();
}

export function GET() {
  const posts = getPublishedPosts();
  const latestPostDate = posts.map(postUpdatedAt).sort().at(-1);
  const entries: SitemapEntry[] = [
    { path: '/', lastmod: latestPostDate, changefreq: 'daily', priority: '1.0' },
    { path: '/archive/', lastmod: latestPostDate, changefreq: 'weekly', priority: '0.7' },
    { path: '/tags/', lastmod: latestPostDate, changefreq: 'weekly', priority: '0.6' },
    { path: '/site-map/', lastmod: latestPostDate, changefreq: 'weekly', priority: '0.5' },
    ...Array.from({ length: Math.max(0, getTotalPages(posts) - 1) }, (_, index) => ({
      path: `/page/${index + 2}/`,
      lastmod: latestPostDate,
      changefreq: 'weekly' as const,
      priority: '0.6'
    })),
    ...getTagSummaries().map((tag) => ({
      path: `/tags/${tag.slug}/`,
      lastmod: latestPostDate,
      changefreq: 'weekly' as const,
      priority: '0.5'
    })),
    ...posts.map((post) => ({
      path: post.url,
      lastmod: postUpdatedAt(post),
      changefreq: 'monthly' as const,
      priority: '0.8'
    }))
  ];

  const body = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${entries
  .map((entry) => {
    const lastmod = formatLastmod(entry.lastmod);
    return `  <url>
    <loc>${xmlEscape(absoluteUrl(entry.path))}</loc>${lastmod ? `\n    <lastmod>${lastmod}</lastmod>` : ''}
    <changefreq>${entry.changefreq ?? 'weekly'}</changefreq>
    <priority>${entry.priority ?? '0.5'}</priority>
  </url>`;
  })
  .join('\n')}
</urlset>`;

  return new Response(body, {
    headers: {
      'Content-Type': 'application/xml; charset=utf-8',
      'Cache-Control': 'public, max-age=3600'
    }
  });
}
