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

export const dynamic = 'force-dynamic';

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

  const sitemapEntries: MetadataRoute.Sitemap = [];

  for (const locale of locales) {
    // Helper to generate localized URL Segment
    const getLocalizedRoute = async (pageKey: string) => {
      if (pageKey === '') return '';
      const translated = await mapFileSlugToTranslated(pageKey, locale);
      return `/${translated}`;
    };

    // Static routes
    const staticPages = ['', 'blog', 'contact', 'team', 'products'];
    for (const page of staticPages) {
      const localizedRoute = await getLocalizedRoute(page);
      sitemapEntries.push({
        url: `${baseUrl}/${locale}${localizedRoute}`,
        lastModified: new Date(),
        changeFrequency: page === '' ? 'daily' : 'weekly',
        priority: page === '' ? 1 : 0.8,
      });
    }

    // Categories routes
    const productCategories = [
      'low-voltage-cables',
      'medium-voltage-cables',
      'high-voltage-cables',
      'solar-cables',
    ];

    const translatedProducts = await mapFileSlugToTranslated('products', locale);

    for (const category of productCategories) {
      const translatedCategory = await mapFileSlugToTranslated(category, locale);
      sitemapEntries.push({
        url: `${baseUrl}/${locale}/${translatedProducts}/${translatedCategory}`,
        lastModified: new Date(),
        changeFrequency: 'weekly',
        priority: 0.8,
      });
    }

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

      const firstCat = product.frontmatter.categories[0] || '';
      const normalizedCat = firstCat.toLowerCase().replace(/\s+/g, '-');
      let categoryFileSlug = 'low-voltage-cables';
      if (normalizedCat === 'hochspannungskabel' || normalizedCat === 'high-voltage-cables')
        categoryFileSlug = 'high-voltage-cables';
      else if (
        normalizedCat === 'mittelspannungskabel' ||
        normalizedCat === 'medium-voltage-cables'
      )
        categoryFileSlug = 'medium-voltage-cables';
      else if (
        normalizedCat === 'solarkabel' ||
        normalizedCat === 'solar-cables' ||
        normalizedCat === 'solar'
      )
        categoryFileSlug = 'solar-cables';

      const translatedCategory = await mapFileSlugToTranslated(categoryFileSlug, locale);
      const translatedSlug = await mapFileSlugToTranslated(product.slug, locale);

      sitemapEntries.push({
        url: `${baseUrl}/${locale}/${translatedProducts}/${translatedCategory}/${translatedSlug}`,
        lastModified: new Date(),
        changeFrequency: 'monthly',
        priority: 0.7,
      });
    }

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

      const translatedSlug = await mapFileSlugToTranslated(post.slug, locale);

      sitemapEntries.push({
        url: `${baseUrl}/${locale}/${translatedBlog}/${translatedSlug}`,
        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;

      const translatedSlug = await mapFileSlugToTranslated(page.slug, locale);

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

  return sitemapEntries;
}
