import { config } from '@/lib/config';
import { MetadataRoute } from 'next';
import { getAllProductsMetadata } from '@/lib/mdx';
import { getAllPostsMetadata } from '@/lib/blog';
import { getAllPagesMetadata } from '@/lib/pages';

export const revalidate = 3600; // Revalidate every hour

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const baseUrl = config.baseUrl || 'https://klz-cables.com';
  const locales = ['de', 'en'];

  const routes = [
    '',
    '/blog',
    '/contact',
    '/team',
    '/products',
    '/products/low-voltage-cables',
    '/products/medium-voltage-cables',
    '/products/high-voltage-cables',
    '/products/solar-cables',
  ];

  const sitemapEntries: MetadataRoute.Sitemap = [];

  for (const locale of locales) {
    // Static routes
    for (const route of routes) {
      sitemapEntries.push({
        url: `${baseUrl}/${locale}${route}`,
        lastModified: new Date(),
        changeFrequency: route === '' ? 'daily' : 'weekly',
        priority: route === '' ? 1 : 0.8,
      });
    }

    // Products
    const productsMetadata = await getAllProductsMetadata(locale);
    for (const product of productsMetadata) {
      if (!product.frontmatter || !product.slug) continue;

      const category =
        product.frontmatter.categories[0]?.toLowerCase().replace(/\s+/g, '-') || 'other';
      sitemapEntries.push({
        url: `${baseUrl}/${locale}/products/${category}/${product.slug}`,
        lastModified: new Date(),
        changeFrequency: 'monthly',
        priority: 0.7,
      });
    }

    // Blog posts
    const postsMetadata = await getAllPostsMetadata(locale);
    for (const post of postsMetadata) {
      if (!post.frontmatter || !post.slug) continue;

      sitemapEntries.push({
        url: `${baseUrl}/${locale}/blog/${post.slug}`,
        lastModified: new Date(post.frontmatter.date),
        changeFrequency: 'monthly',
        priority: 0.6,
      });
    }

    // Static pages
    const pagesMetadata = await getAllPagesMetadata(locale);
    for (const page of pagesMetadata) {
      if (!page.slug) continue;

      sitemapEntries.push({
        url: `${baseUrl}/${locale}/${page.slug}`,
        lastModified: new Date(),
        changeFrequency: 'monthly',
        priority: 0.5,
      });
    }
  }

  return sitemapEntries;
}
